您的位置:首页 > Web前端

[279]Perfect Squares

2015-11-07 12:40 411 查看
【题目描述】

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
.
【思路】
1.用动态规划。f[i]=min(f[i],f[i-j*j])

2.根据四平方和定理和https://leetcode.com/discuss/56982/o-sqrt-n-in-ruby-and-c,

... a square if and only if each prime factor occurs to an even power in the number's prime factorization.
... a sum of two squares if
and only if each prime factor that's 3 modulo 4 occurs to an even power in the number's prime factorization.
... a sum of three squares if
and only if it's not of the form 4a(8b+7) with integers a and b.
... a sum of four squares.
Period. No condition. You never need more than four。

【代码】

<span style="font-size:14px;">class Solution {
public:
int numSquares(int n) {
vector<int> f(n+1,INT_MAX);
for(int i=1;i*i<=n;i++){
f[i*i]=1;
}
for(int i=2;i<=n;i++){
if(f[i]==1) continue;
for(int j=1;j*j<i;j++){
f[i]=min(f[i],f[i-j*j]+1);
}
}
return f
;
}
};</span>
class Solution {
public:
int numSquares(int n) {
while(n%4==0) n/=4;
if(n%8==7) return 4;
for(int i=0;i*i<=n;i++){
int j=sqrt(n-i*i);
if(i*i+j*j==n){
return !!i+!!j;
}
}
return 3;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: