[Leetcode 279] Perfect Squares
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.
解法一:动态规划
class Solution {
public:
int numSquares(int n) {
int sqrt_n = sqrt(n) + 0.5;
vector<int> a(sqrt_n + 1);
for(int i = 1; i <= sqrt_n; ++i)
a[i] = i * i;
vector<int> b(n+1, 1000);
b[0] = 0;
for(int i = 1; i <= n; ++i){
for(int j = sqrt(i); j >= 1; --j)
b[i] = min(b[i], b[i - a[j]] + 1);
return b[n];
}
};
解法二:拉格朗日四平方定理
class Solution {
bool is_sqrt(int n){
int sqrt_n = sqrt(n);
return (n == sqrt_n * sqrt_n);
}
public:
int numSquares(int n) {
if(is_sqrt(n)) return 1;
while((n & 3) == 0) n >>= 2;
if((n & 7) == 7) return 4;
if((n & 1) == 0) n >>= 1;
int sqrt_n = sqrt(n);
if(sqrt_n & 1 == 0) sqrt_n--;
for(int i = sqrt_n; i > 0; i -= 2){
if(is_sqrt(n - i*i)) {
return 2;
}
}
return 3;
}
};
1万+



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



