forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution2.java
39 lines (28 loc) · 892 Bytes
/
Solution2.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/// Source : https://leetcode.com/problems/perfect-squares/description/
/// Author : liuyubobobo
/// Time : 2017-11-17
import java.util.Arrays;
/// Memory Search
/// Time Complexity: O(n)
/// Space Complexity: O(n)
public class Solution2 {
public int numSquares(int n) {
int[] mem = new int[n+1];
Arrays.fill(mem, -1);
return numSquares(n, mem);
}
private int numSquares(int n, int[] mem){
if(n == 0)
return 0;
if(mem[n] != -1)
return mem[n];
int res = Integer.MAX_VALUE;
for(int i = 1; n - i * i >= 0; i ++ )
res = Math.min(res, 1 + numSquares(n - i * i, mem));
return mem[n] = res;
}
public static void main(String[] args) {
System.out.println((new Solution2()).numSquares(12));
System.out.println((new Solution2()).numSquares(13));
}
}