Problem
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
Example
given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.
Algorithm
整理一下题意:给定一个正整数n,要求找到一组平方数使得其加起来的和等于n且这组数的个数最少,返回这组数的个数。
使用动态规划的思路解决。设f(i)表示i对应平方数组合最小个数,则f(i)必然等于最小的f[i-平方数]再加一,即状态转移方程为
f[i]=min(f[i-squ[j])+1;
于是f(n)即为解。
代码如下。
class Solution {
public:
int numSquares(int n) {
vector<int> f(n+1,0);
f[1]=1;
for(int i=2;i<n+1;i++){
int min=INT_MAX;
for(int j=1;j<=sqrt(n);j++){
if(i-j*j>=0&&min>f[i-j*j]) min=f[i-j*j];
}
f[i]=min+1;
}
return f[n];
}
};