Skip to content

Commit 07ccccc

Browse files
committed
Add a solution for LeetCode #473
1 parent f643970 commit 07ccccc

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package org.sean.backtracking
2+
3+
import java.util.*
4+
5+
/***
6+
* 473. Matchsticks to Square
7+
*/
8+
class StickSquare {
9+
private lateinit var visited: BooleanArray
10+
11+
private fun makesquareHelper(edges: Int, nums: IntArray, target: Int, sum: Int, pos: Int): Boolean {
12+
if (edges == 4) {
13+
return true
14+
}
15+
if (edges > 4) {
16+
return false
17+
}
18+
if (sum == target) return makesquareHelper(edges + 1, nums, target, 0, 0)
19+
20+
for (i in pos until nums.size) {
21+
if (visited[i]) continue
22+
if (sum + nums[i] > target) continue
23+
24+
visited[i] = true
25+
if (makesquareHelper(edges, nums, target, sum + nums[i], i + 1)) {
26+
return true
27+
}
28+
visited[i] = false
29+
}
30+
return false
31+
}
32+
33+
/***
34+
* The problem is very similar to [SubsetPartition]
35+
*/
36+
fun makesquare(matchsticks: IntArray): Boolean {
37+
if (matchsticks.size < 4) return false
38+
val sum = Arrays.stream(matchsticks).sum()
39+
if (sum % 4 != 0) return false
40+
val edgeLen = sum / 4
41+
if (Arrays.stream(matchsticks).max().asInt > edgeLen) return false
42+
visited = BooleanArray(matchsticks.size)
43+
Arrays.sort(matchsticks)
44+
45+
return makesquareHelper(0, matchsticks, edgeLen, 0, 0)
46+
}
47+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package org.sean.backtracking
2+
3+
import org.junit.Before
4+
import org.junit.Test
5+
6+
import org.junit.Assert.*
7+
8+
class StickSquareTest {
9+
lateinit var square: StickSquare
10+
11+
@Before
12+
fun setUp() {
13+
square = StickSquare()
14+
}
15+
16+
@Test
17+
fun makesquare() {
18+
assert(square.makesquare(intArrayOf(5, 5, 5, 5, 4, 4, 4, 4, 3, 3, 3, 3)))
19+
}
20+
}

0 commit comments

Comments
 (0)