Skip to content

Commit 6561b5d

Browse files
authored
Create 0473-matchsticks-to-square.kt
1 parent 6f8f113 commit 6561b5d

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

kotlin/0473-matchsticks-to-square.kt

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution {
2+
fun makesquare(matchsticks: IntArray): Boolean {
3+
val length = matchsticks.sum()!! / 4
4+
val sides = IntArray (4)
5+
6+
if (matchsticks.sum()!! / 4 != length) return false
7+
8+
matchsticks.sortDescending()
9+
10+
fun backtrack(i: Int): Boolean {
11+
if (i == matchsticks.size) return true
12+
13+
for (j in 0..3) {
14+
if (sides[j] + matchsticks[i] <= length) {
15+
sides[j] += matchsticks[i]
16+
if (backtrack(i + 1))
17+
return true
18+
sides[j] -= matchsticks[i]
19+
}
20+
}
21+
22+
return false
23+
}
24+
25+
return backtrack(0)
26+
}
27+
}

0 commit comments

Comments
 (0)