Skip to content

Commit 6a187c0

Browse files
committed
Runtime: 3 ms (Top 98.54%) | Memory: 42 MB (Top 43.12%)
1 parent 91ea9ad commit 6a187c0

File tree

1 file changed

+17
-16
lines changed

1 file changed

+17
-16
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1+
// Runtime: 3 ms (Top 98.54%) | Memory: 42 MB (Top 43.12%)
12
/*
23
Time complexity: O(2 ^ n)
34
Space complexity: O(n)
4-
5+
56
Inutition:
67
---------
78
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,
1617
// if one of the side is found then keep finding the other k - 1 sides starting again from the beginning
1718
return backtrack(nums, 0, k - 1, 0, target, vis);
1819
}
19-
20+
2021
// hypothesis
2122
for(int i = idx; i < nums.length; i++) {
2223
// if number is already visited or sum if out of range then skip
2324
if (vis[i] || subsetSum + nums[i] > target)
2425
continue;
25-
26+
2627
// 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,
2829
// 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])
3031
continue;
31-
32+
3233
vis[i] = true;
3334
if (backtrack(nums, i + 1, k, subsetSum + nums[i], target, vis))
3435
return true;
35-
36+
3637
// backtrack
3738
vis[i] = false;
3839
}
39-
40+
4041
return false;
4142
}
42-
43+
4344
private void reverse(int[] arr) {
4445
for (int i = 0, j = arr.length - 1; i < j; i++, j--) {
4546
int tmp = arr[i];
4647
arr[i] = arr[j];
4748
arr[j] = tmp;
4849
}
4950
}
50-
51+
5152
public boolean makesquare(int[] matchsticks) {
5253
int sum = 0;
5354
int k = 4;
5455
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
5657
Arrays.sort(matchsticks);
5758
reverse(matchsticks);
58-
59+
5960
for(int match: matchsticks)
6061
sum += match;
61-
62+
6263
if (sum % k != 0)
6364
return false;
64-
65+
6566
int target = sum / k;
6667
boolean[] vis = new boolean[n];
67-
68+
6869
return backtrack(matchsticks, 0, k, 0, target, vis);
6970
}
70-
}
71+
}

0 commit comments

Comments
 (0)