[LeetCode] Perfect Squares

简介: 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.

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.

 1 class Solution {
 2 public:
 3     int numSquares(int n) {
 4         vector<int> dp(n + 1);
 5         iota(dp.begin(), dp.end(), 0);
 6         int ub = sqrt(n), next;
 7         for (int i = 0; i <= n; i++) {
 8             for (int j = 1; j <= ub; j++) {
 9                 next = i + j * j;
10                 if (next > n) break;
11                 dp[next] = min(dp[next], dp[i] + 1);
12             }
13         }
14         return dp[n];
15     }
16 };

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 -_-).

 1 class Solution {
 2 public:
 3     int numSquares(int n) {
 4         while (!(n % 4)) n /= 4;
 5         if (n % 8 == 7) return 4;
 6         for (int a = 0; a * a <= n; a++) {
 7             int b = sqrt(n - a * a);
 8             if (a * a + b * b == n)
 9                 return !!a + !!b;
10         }
11         return 3;
12     }
13 };

 

目录
相关文章
LeetCode 367. Valid Perfect Square
给定一个正整数 num,编写一个函数,如果 num 是一个完全平方数,则返回 True,否则返回 False。
59 0
LeetCode 367. Valid Perfect Square
LeetCode 279. Perfect Squares
给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。
48 0
LeetCode 279. Perfect Squares
Leetcode-Easy 977. Squares of a Sorted Array
Leetcode-Easy 977. Squares of a Sorted Array
77 0
[LeetCode] 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; give
1050 0
|
29天前
|
机器学习/深度学习 算法
力扣刷题日常(一)
力扣刷题日常(一)
20 2
|
1月前
|
存储 索引
《LeetCode》—— LeetCode刷题日记
《LeetCode》—— LeetCode刷题日记
|
1月前
|
搜索推荐
《LeetCode》——LeetCode刷题日记3
《LeetCode》——LeetCode刷题日记3