题目
- Total Accepted: 73644
- Total Submissions: 203690
- Difficulty: Medium
- Contributor: LeetCode
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
.
思路
题目给定一个整数,希望求得能用平方数相加得到这个整数是的最少的平方数的个数。
使用动态规划,使用r[i]保存整数i的结果,动态方程为r[i] =min{r[i - j * j] + 1}。
源程序
class Solution {
public:
int numSquares(int n) {
int i,j,t;
int r[100000];
r[0] = 0;
r[1] = 1;
for(i = 2;i <= n;i ++){
t = 999999;
j = 1;
while(j * j <= i){
if((r[i - j * j] + 1) < t)
t = r[i - j * j] + 1;
j ++;
}
r[i] = t;
}
return r[n];
}
};