Question
Formatted question description: https://leetcode.ca/all/279.html
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.
Example 1:
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.
Example 2:
Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.
@tag-dp
Algorithm
Create a one-dimensional dp array of length n+1, initialize the first value to 0, and initialize the remaining values to INT_MAX
i loops from 0 to n, j loops from 1 to the position of i+jj <= n, and then updates the value of dp[i+jj] each time, dynamically updating the dp array, where dp[i] means positive The integer i can be composed of multiple perfect squares.
Note that the wording here, i must start from 0, j must start from 1. Because our original intention is to use dp[i] to update dp[i + j * j], if i=0, j=1 , Then dp[i] and dp[i + j * j] are equal.
Code
Java
import java.util.Arrays;
public class Perfect_Squares {
public static void main(String[] args) {
Perfect_Squares out = new Perfect_Squares();
Solution s = out.new Solution();
System.out.println(s.numSquares(43));
}
class Solution_lessLoop {
public int numSquares(int n) {
if (n <= 0) {
return 0;
}
// count[i] means, for number i, minimum square count
int[] dp = new int[n + 1];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
for (int i = 0; i <= n; ++i) {
for (int j = 1; i + j * j <= n; ++j) {
dp[i + j * j] = Math.min(dp[i + j * j], dp[i] + 1);
}
}
return dp[n];
}
}
class Solution {
public int numSquares(int n) {
if (n <= 0) {
return 0;
}
// count[i] means, for number i, minimum square count
int[] count = new int[n + 1];
Arrays.fill(count, Integer.MAX_VALUE);
count[0] = 0;
// fill in sqaures first
int maxPossibleSqaureRoot = (int)Math.sqrt(n * 1.0);
for (int i = 1; i <= maxPossibleSqaureRoot; i++) {
count[(int)Math.pow(i, 2)] = 1;
}
for (int i = 1; i <= n; i++) {
int start = 0;
int end = i / 2;
for (int j = start; j <= end; j++) {
count[i] = Math.min(count[i], count[j] + count[i - j]);
}
}
return count[n];
}
}
}