|
1 | 1 | package g0401_0500.s0473_matchsticks_to_square;
|
2 | 2 |
|
3 | 3 | // #Medium #Array #Dynamic_Programming #Bit_Manipulation #Backtracking #Bitmask
|
4 |
| -// #2022_03_18_Time_241_ms_(18.95%)_Space_42.1_MB_(40.60%) |
| 4 | +// #2022_07_14_Time_161_ms_(55.12%)_Space_40.4_MB_(88.85%) |
| 5 | + |
| 6 | +import java.util.Arrays; |
5 | 7 |
|
6 | 8 | public class Solution {
|
7 | 9 | public boolean makesquare(int[] matchsticks) {
|
8 | 10 | if (matchsticks.length < 4) {
|
9 | 11 | return false;
|
10 | 12 | }
|
11 |
| - int totalSum = 0; |
12 |
| - for (int m : matchsticks) { |
13 |
| - totalSum += m; |
| 13 | + int per = 0; |
| 14 | + for (int ele : matchsticks) { |
| 15 | + per = ele + per; |
14 | 16 | }
|
15 |
| - if (totalSum % 4 != 0) { |
| 17 | + if (per % 4 != 0) { |
16 | 18 | return false;
|
17 | 19 | }
|
18 |
| - int target = totalSum / 4; |
19 |
| - boolean[] used = new boolean[matchsticks.length]; |
20 |
| - return backtracking(matchsticks, used, target, 0, 0, 0); |
| 20 | + Arrays.sort(matchsticks); |
| 21 | + int side = per / 4; |
| 22 | + int[] sides = new int[] {side, side, side, side}; |
| 23 | + return help(matchsticks, matchsticks.length - 1, sides); |
21 | 24 | }
|
22 | 25 |
|
23 |
| - private boolean backtracking( |
24 |
| - int[] matchsticks, boolean[] used, int target, int count, int currSum, int start) { |
25 |
| - if (count == 3) { |
26 |
| - return true; |
27 |
| - } |
28 |
| - if (currSum > target) { |
29 |
| - return false; |
| 26 | + private boolean help(int[] nums, int i, int[] side) { |
| 27 | + if (i == -1) { |
| 28 | + return side[0] == 0 && side[1] == 0 && side[2] == 0 && side[3] == 0; |
30 | 29 | }
|
31 |
| - if (currSum == target) { |
32 |
| - return backtracking(matchsticks, used, target, count + 1, 0, 0); |
33 |
| - } |
34 |
| - for (int i = start; i < matchsticks.length; i++) { |
35 |
| - if (!used[i]) { |
36 |
| - used[i] = true; |
37 |
| - if (backtracking( |
38 |
| - matchsticks, used, target, count, currSum + matchsticks[i], i + 1)) { |
39 |
| - return true; |
40 |
| - } |
41 |
| - used[i] = false; |
| 30 | + for (int j = 0; j < 4; j++) { |
| 31 | + if (nums[i] > side[j]) { |
| 32 | + continue; |
| 33 | + } |
| 34 | + side[j] -= nums[i]; |
| 35 | + if (help(nums, i - 1, side)) { |
| 36 | + return true; |
42 | 37 | }
|
| 38 | + side[j] += nums[i]; |
43 | 39 | }
|
44 | 40 | return false;
|
45 | 41 | }
|
|
0 commit comments