您的位置:首页 > Web前端

[LeetCode] Perfect Squares

2015-09-09 22:47 281 查看
Well, after seeing the similar problems, you may have known how to solve this problem. Yeah, just to construct larger numbers from smaller numbers by adding perfect squares to them. This post shares a nice code and is rewritten below.

class Solution {
public:
int numSquares(int n) {
vector<int> dp(n + 1);
iota(dp.begin(), dp.end(), 0);
int ub = sqrt(n), next;
for (int i = 0; i <= n; i++) {
for (int j = 1; j <= ub; j++) {
next = i + j * j;
if (next > n) break;
dp[next] = min(dp[next], dp[i] + 1);
}
}
return dp
;
}
};


Well, you may have noticed that the above code has many repeated computations. For example, for n = 10 and 11, we will recompute dp[0] to dp[10]. So a way to reduce the running time is to use static variables to store those results and return it if it has already been computed. Stefan posts severl nice solutions here.

Finally, the above strategy using static variables does not reduce the expected running time of the algorithm, which is still of O(n^(3/2)). And guess what? There exists a much faster O(n^(1/2)) algorithm using number theory, also posted by Stefan here. I rewrite its clear C solution in C++ below (well, just a copy -_-).

class Solution {
public:
int numSquares(int n) {
while (!(n % 4)) n /= 4;
if (n % 8 == 7) return 4;
for (int a = 0; a * a <= n; a++) {
int b = sqrt(n - a * a);
if (a * a + b * b == n)
return !!a + !!b;
}
return 3;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: