-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStickSquare.kt
47 lines (40 loc) · 1.3 KB
/
StickSquare.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package org.sean.backtracking
import java.util.*
/***
* 473. Matchsticks to Square
*/
class StickSquare {
private lateinit var visited: BooleanArray
private fun makesquareHelper(edges: Int, nums: IntArray, target: Int, sum: Int, pos: Int): Boolean {
if (edges == 4) {
return true
}
if (edges > 4) {
return false
}
if (sum == target) return makesquareHelper(edges + 1, nums, target, 0, 0)
for (i in pos until nums.size) {
if (visited[i]) continue
if (sum + nums[i] > target) continue
visited[i] = true
if (makesquareHelper(edges, nums, target, sum + nums[i], i + 1)) {
return true
}
visited[i] = false
}
return false
}
/***
* The problem is very similar to [SubsetPartition]
*/
fun makesquare(matchsticks: IntArray): Boolean {
if (matchsticks.size < 4) return false
val sum = Arrays.stream(matchsticks).sum()
if (sum % 4 != 0) return false
val edgeLen = sum / 4
if (Arrays.stream(matchsticks).max().asInt > edgeLen) return false
visited = BooleanArray(matchsticks.size)
Arrays.sort(matchsticks)
return makesquareHelper(0, matchsticks, edgeLen, 0, 0)
}
}