Perfect Squares
2015-09-13 14:47
369 查看
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.
思路:其实这道题和青蛙跳台阶的那一道也有点相似。用f(i)表示当n为i的时候,最少的完全平方数的个数。f(i)就等于f(i-1)+f(1) 、f(i-4)+f(4)、f(i-9)+f(9)、、、f(i-k)+f(k),(其中k要小于i) 中最小的一个加上1。其中f(1)、f(4)和f(9)等均为1。那么就反过来求,求f(1)、f(2)、、、,f(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.
思路:其实这道题和青蛙跳台阶的那一道也有点相似。用f(i)表示当n为i的时候,最少的完全平方数的个数。f(i)就等于f(i-1)+f(1) 、f(i-4)+f(4)、f(i-9)+f(9)、、、f(i-k)+f(k),(其中k要小于i) 中最小的一个加上1。其中f(1)、f(4)和f(9)等均为1。那么就反过来求,求f(1)、f(2)、、、,f(n)自然也会有结果了。
public class Solution { public int numSquares(int n) { if(n<=0) return -1; int[] nums=new int[n+1]; int c=1; while(c*c<=n) { nums[c*c]=1; c++; } for(int i=1;i<=n;i++) { if(nums[i]==1) continue; int min=Integer.MAX_VALUE; int j=1; while(j*j<i) { min=min < (nums[i-j*j]+1) ? min : nums[i-j*j]+1; j++; } nums[i]=min; } return nums ; } }
相关文章推荐
- ExtJS4组件_form表单配置-属性-方法详解
- 因为yii2中jquery位置默认在最下方,可将自定义js位置放在下方
- Angular遇上CoffeeScript - NgComponent封装
- js原生removeclass方法
- JQuery源码之“对象的结构解析”
- CSS解决未知高度的垂直水平居中自适应问题
- javascript严格模式下的8点规则
- 来访统计的JS代码
- 原生js--客户端存储的种类
- CSS 阴影怎么写?
- js面向对象的例子(私有/公有/特权方法)-2
- react-利用Atom搭建开发环境
- jquery select三级联动
- GMT5.1.2_基础_坐标轴的设置和离散点的样式控制
- Javascript匿名函数
- json与xml对比
- HTML精确定位:scrollLeft,scrollWidth,clientWidth,offsetWidth之完全详解
- Angular.js 与script.js 异步加载
- Javascript继承(暂略去中转函数、组合继承和寄生继承)
- js面向对象的例子-1