279.Perfect Squares

Dynamic Programming, Medium

Question

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:

1
2
3
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.

Example 2:

1
2
3
Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.

Answer

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public int numSquares(int n) {
int[] res = new int[n+1];
Arrays.fill(res, Integer.MAX_VALUE);
res[0] = 0;
for(int i = 1; i <= n; i++)
for(int j = 1; j * j <= i; j++)
res[i] = Math.min(res[i], res[i - j * j] + 1); // plus one, one means add j, which could get n
return res[n];
}
}

Time complexity: O(n * logn)

Space complexity: O(n)