File tree 1 file changed +9
-22
lines changed
1 file changed +9
-22
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
- Set <Integer > squareNums ;
3
2
public int numSquares (int n ) {
4
- squareNums = new HashSet <>();
5
- for (int i = 1 ; i * i <= n ; i ++) {
6
- squareNums .add (i * i );
7
- }
8
- int count = 1 ;
9
- for (count = 1 ; count <= n ; count ++) {
10
- if (isDividedBy (n , count )) {
11
- return count ;
12
- }
13
- }
14
- return count ;
15
- }
16
-
17
- private boolean isDividedBy (int n , int count ) {
18
- if (count == 1 ) {
19
- return squareNums .contains (n );
20
- }
21
- for (Integer squareNum : squareNums ) {
22
- if (isDividedBy (n - squareNum , count - 1 )) {
23
- return true ;
3
+ int [] dp = new int [n + 1 ];
4
+ Arrays .fill (dp , Integer .MAX_VALUE );
5
+ dp [0 ] = 0 ;
6
+ for (int i = 1 ; i <= n ; i ++) {
7
+ int min = Integer .MAX_VALUE ;
8
+ for (int j = 1 ; i - j * j >= 0 ; j ++) {
9
+ min = Math .min (min , dp [i - j * j ] + 1 );
24
10
}
11
+ dp [i ] = min ;
25
12
}
26
- return false ;
13
+ return dp [ n ] ;
27
14
}
28
15
}
You can’t perform that action at this time.
0 commit comments