1.问题描述
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.
2.解答
class Solution {
public:
int numSquares(int n)
{
int *temp=new int[n+1];
int min=0;
*temp=0;
for(int i=0;i<n+1;i++)
temp[i]=0;
for(int i=1;i<=sqrt(n);i++)
{
temp[i*i]=1;
}
for(int i=2;i<=n;i++)
{
if(temp[i]!=1)
{
min=10000;
for(int j=1;j<sqrt(i);j++)
{
int a=temp[j*j]+temp[i-j*j];
if(a<min)
min=a;
}
temp[i]=min;
}
}
int res=temp[n];
delete []temp;
return res;
}
};
本文介绍了一个算法,用于找到给定整数n的最小完美平方数之和。通过迭代计算并存储已知的最小组合,算法最终确定了n的最佳分解方式。
530

被折叠的 条评论
为什么被折叠?



