Perfect Squares
Given an integer n, return the least number of perfect square numbers (1, 4, 9, 16, ...) that sum to n.
Example 1
Input: 12 → Output: 3 (4+4+4)
Example 2
Input: 13 → Output: 2 (4+9)
Solution Approach
DP: dp[i] = minimum number of perfect squares summing to i. For each i, try all perfect squares <= i.
- Initialize dp[] with i (worst case: all 1s).
- For each i from 1 to n: for each j where j*j <= i: dp[i] = min(dp[i], dp[i-j*j]+1).
- Return dp[n].
Java
class Solution {
public int numSquares(int n) {
int[] dp = new int[n + 1];
java.util.Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j * j <= i; j++) {
dp[i] = Math.min(dp[i], dp[i - j * j] + 1);
}
}
return dp[n];
}
}
- Time Complexity: O(N * sqrt(N))
- Space Complexity: O(N)