首页 > 其他 > 详细

LeetCode-Perfect Squares

时间:2016-09-01 12:46:03      阅读:123      评论:0      收藏:0      [点我收藏+]

Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.

For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Analysis:

A DP solution like the Coin Changes.

Solution:

 1 public class Solution {
 2     public int numSquares(int n) {
 3         int[] nums = new int[n+1];
 4 
 5         for (int i=1;i<=n;i++){
 6             nums[i] = Integer.MAX_VALUE;
 7             for (int j=1;j*j<=i;j++){
 8                 nums[i] = Math.min(nums[i], nums[i-j*j]+1);
 9             }
10         }
11         return nums[n];
12     }
13 }

 

LeetCode-Perfect Squares

原文:http://www.cnblogs.com/lishiblog/p/5829322.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!