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
.
思路:
ans[12] = min( ans[12-9]+1, ans[12-4]+1, ans[12-1]+1 );
最初是用递归方法做,但超时了,因为涉及了许多重复计算;
后采用数组方式,记录中间计算结果,从1计算到n;
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 class Solution { 2 public: 3 int numSquares(int n) { 4 vector<int> ans(n+1,0); 5 ans[1] = 1; 6 for(int i=2;i<=n;i++) 7 { 8 int s = sqrt(i); 9 if(s*s == i) 10 ans[i] = 1; 11 else 12 { 13 int tmp = i; 14 for(int j=s;j>=1;j--) 15 { 16 int tmp2 = ans[i-j*j]+1; 17 if(tmp2<tmp) 18 tmp = tmp2; 19 } 20 ans[i] = tmp; 21 } 22 } 23 return ans[n]; 24 } 25 };