leetcode Perfect Squares
2016-07-22 21:44
585 查看
Given a positive integer n, find the least number of perfect square numbers (for example,
For example, given n =
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
经典dp题目,dp题目最重要的是找状态转移方程,https://segmentfault.com/a/1190000003768736讲的非常清楚,这道题是为了找构成整数所需的最小个数的平方数,可以理解为若n=a+b*b,那么n所需的最小平方数个数为a所需的最小平方数个数+1,如果能想到这里这道题基本就解决了,我们只需要找到小于等于n的所有平方数,将他们的初值设为1,然后进行比较即可,代码:
1, 4, 9, 16, ...) which sum to n.
For example, given n =
12, return
3because
12 = 4 + 4 + 4; given n =
13, return
2because
13 = 4 + 9.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
经典dp题目,dp题目最重要的是找状态转移方程,https://segmentfault.com/a/1190000003768736讲的非常清楚,这道题是为了找构成整数所需的最小个数的平方数,可以理解为若n=a+b*b,那么n所需的最小平方数个数为a所需的最小平方数个数+1,如果能想到这里这道题基本就解决了,我们只需要找到小于等于n的所有平方数,将他们的初值设为1,然后进行比较即可,代码:
public int numSquares(int n) { int[] res=new int[n+1]; Arrays.fill(res,Integer.MAX_VALUE); for(int i=0;i*i<=n;i++){ res[i*i]=1; } for(int a=0;a<=n;a++){ for(int b=0;a+b*b<=n;b++){ res[a+b*b]=Math.min(res[a]+1,res[a+b*b]); } } return res ; }
相关文章推荐
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- C#递归算法之分而治之策略
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- C#算法之大牛生小牛的问题高效解决方法
- C#算法函数:获取一个字符串中的最大长度的数字
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- 经典排序算法之冒泡排序(Bubble sort)代码
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法