Skip to content

Commit f74063e

Browse files
Merge pull request #2980 from rohankayan/main
Create: 0473-matchsticks-to-square.java
2 parents cd768c3 + 7a18c24 commit f74063e

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Diff for: java/0473-matchsticks-to-square.java

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Solution {
2+
boolean[] used;
3+
public boolean makesquare(int[] matchsticks) {
4+
used = new boolean[matchsticks.length];
5+
int total = 0;
6+
for (int n : matchsticks) {
7+
total += n;
8+
}
9+
//Check if total of all the sides is divisible by 4 or not
10+
if (total % 4 != 0) return false;
11+
int side = total / 4;
12+
13+
return helper(matchsticks, side, 0, 0, 4);
14+
}
15+
16+
boolean helper(int[] matchsticks, int targetSide, int currentSum, int index, int sides) {
17+
//if all the sides are matching the target side length then we found a solution
18+
if (sides == 0)
19+
return true;
20+
//Check if current side is equal to targetSide , that means we found another side
21+
if (currentSum == targetSide) {
22+
return helper(matchsticks, targetSide, 0, 0, sides - 1);
23+
}
24+
25+
for (int i = index; i < matchsticks.length; i++) {
26+
//Only use matchsticks which are not used and which doesn't increase the current side more than target side
27+
if (!used[i] && currentSum + matchsticks[i] <= targetSide) {
28+
used[i] = true;
29+
boolean found = helper(matchsticks, targetSide, currentSum + matchsticks[i], i + 1, sides);
30+
if (found) {
31+
return true;
32+
}
33+
used[i] = false;
34+
}
35+
}
36+
return false;
37+
}
38+
39+
40+
}

0 commit comments

Comments
 (0)