1
+ // Runtime: 3 ms (Top 98.54%) | Memory: 42 MB (Top 43.12%)
1
2
/*
2
3
Time complexity: O(2 ^ n)
3
4
Space complexity: O(n)
4
-
5
+
5
6
Inutition:
6
7
---------
7
8
Same as "Partition to K Equal Sum Subsets"
@@ -16,55 +17,55 @@ public boolean backtrack(int[] nums, int idx, int k, int subsetSum, int target,
16
17
// if one of the side is found then keep finding the other k - 1 sides starting again from the beginning
17
18
return backtrack (nums , 0 , k - 1 , 0 , target , vis );
18
19
}
19
-
20
+
20
21
// hypothesis
21
22
for (int i = idx ; i < nums .length ; i ++) {
22
23
// if number is already visited or sum if out of range then skip
23
24
if (vis [i ] || subsetSum + nums [i ] > target )
24
25
continue ;
25
-
26
+
26
27
// Pruning
27
- // if the last position (i - 1) is not visited, that means the current combination didn't work,
28
+ // if the last position (i - 1) is not visited, that means the current combination didn't work,
28
29
// and since this position (i) has the same value, it won't work for it as well. Thus, skip it.
29
- if (i - 1 >= 0 && nums [i ] == nums [i - 1 ] && !vis [i - 1 ])
30
+ if (i - 1 >= 0 && nums [i ] == nums [i - 1 ] && !vis [i - 1 ])
30
31
continue ;
31
-
32
+
32
33
vis [i ] = true ;
33
34
if (backtrack (nums , i + 1 , k , subsetSum + nums [i ], target , vis ))
34
35
return true ;
35
-
36
+
36
37
// backtrack
37
38
vis [i ] = false ;
38
39
}
39
-
40
+
40
41
return false ;
41
42
}
42
-
43
+
43
44
private void reverse (int [] arr ) {
44
45
for (int i = 0 , j = arr .length - 1 ; i < j ; i ++, j --) {
45
46
int tmp = arr [i ];
46
47
arr [i ] = arr [j ];
47
48
arr [j ] = tmp ;
48
49
}
49
50
}
50
-
51
+
51
52
public boolean makesquare (int [] matchsticks ) {
52
53
int sum = 0 ;
53
54
int k = 4 ;
54
55
int n = matchsticks .length ;
55
- // sort the array in descending order to make the recursion hit the base case quicker
56
+ // sort the array in descending order to make the recursion hit the base case quicker
56
57
Arrays .sort (matchsticks );
57
58
reverse (matchsticks );
58
-
59
+
59
60
for (int match : matchsticks )
60
61
sum += match ;
61
-
62
+
62
63
if (sum % k != 0 )
63
64
return false ;
64
-
65
+
65
66
int target = sum / k ;
66
67
boolean [] vis = new boolean [n ];
67
-
68
+
68
69
return backtrack (matchsticks , 0 , k , 0 , target , vis );
69
70
}
70
- }
71
+ }
0 commit comments