forked from realpacific/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAllSubsets.kt
36 lines (30 loc) · 866 Bytes
/
AllSubsets.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
package algorithmdesignmanualbook.heuristics.backtrack
class AllSubsets(private val nums: Array<Int>) {
private val result = mutableListOf<MutableList<Int>>()
fun execute(): List<List<Int>> {
if (nums.isEmpty()) {
return result
}
backtrack(0, mutableListOf())
return result
}
private fun backtrack(index: Int, current: MutableList<Int>) {
result.add(ArrayList(current))
for (i in index..nums.lastIndex) {
println("adding " + nums[i])
current.add(nums[i])
backtrack(i + 1, current)
current.removeLastOrNull().also {
println("rm " + it)
}
}
}
}
fun main() {
run {
val solution = AllSubsets(arrayOf(1, 2, 3))
solution.execute().forEach {
println(it)
}
}
}