Description
Given an integer n, return the least number of perfect square numbers that sum to n.
A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.
Examples
Example 1:
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.
Example 2:
Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.
Constraints:
1 <= n <= 1 0 4 10^4 104
思路
最开始就是dp的思路,这里因为给出了constraints,所以有两种方案,一种是对每个数字都判断一遍是不是square,然后向前做dp;还有一种是预先算好所有的perfectSquare,再逐一判断,后者能比前者快5倍。
但后来发现有mathematic ways,就是一个数最多由4个完全平方数组成,而且各自的情况都可以枚举
- 4-square theorem
如果 n 是 4 的倍数,那 n 的组成和 n / 4 的组成一致 - 3-square theorem
如果 n 除 8 余 7,那 n 由 4 个完全平方数组成 - 余下的数字,要么由 2 个完全平方数组成,要么由 3 个完全平方数组成,通过枚举判断
代码
DP1
class Solution {
public int numSquares(int n) {
List<Integer> perfectSquare = new ArrayList<>();
int[] save = new int[n + 1];
save[0] = 0;
for (int i = 1; i <= n; i++){
if (Math.sqrt(i) == (int)Math.sqrt(i)){
save[i] = 1;
perfectSquare.add(i);
}
save[i] = Integer.MAX_VALUE;
for (int ps: perfectSquare){
save[i] = Math.min(save[i], save[i - ps] + 1);
}
}
return save[n];
}
}
DP1
class Solution {
public int numSquares(int n) {
int[] perfectSquare = new int[100];
int[] save = new int[n + 1];
save[0] = 0;
for (int i = 1; i < 101; i++) {
perfectSquare[i - 1] = i * i;
}
for (int i = 1; i <= n; i++){
save[i] = Integer.MAX_VALUE;
for (int j = 0; (perfectSquare[j] <= i && j < 100); j++){
save[i] = Math.min(save[i], save[i - perfectSquare[j]] + 1);
}
}
return save[n];
}
}
Mathematic
class Solution {
boolean isSquare(int n) {
int sq = (int) Math.sqrt(n);
return n == sq * sq;
}
public int numSquares(int n) {
// four-square and three-square theorems.
while (n % 4 == 0)
n /= 4;
if (n % 8 == 7)
return 4;
if (this.isSquare(n))
return 1;
// enumeration to check if the number can be decomposed into sum of two squares.
for (int i = 1; i * i <= n; ++i) {
if (this.isSquare(n - i * i))
return 2;
}
// bottom case of three-square theorem.
return 3;
}
}