-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCombinationSumII.kt
More file actions
30 lines (25 loc) · 933 Bytes
/
CombinationSumII.kt
File metadata and controls
30 lines (25 loc) · 933 Bytes
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
package leetcode
/**
* Problem description on [LeetCode](https://leetcode.com/problems/combination-sum-ii/)
*/
class CombinationSumII {
private val answer = mutableSetOf<List<Int>>()
fun combinationSum2(candidates: IntArray, target: Int): List<List<Int>> {
val list = mutableListOf<Int>()
candidates.sort()
search(candidates, target, 0, list)
return answer.toList()
}
private fun search(candidates: IntArray, target: Int, start: Int, list: MutableList<Int>) {
if (target == 0) answer.add(list.toList())
if (target <= 0) return
var last = 0
for (i in start until candidates.size) {
if (candidates[i] <= target && candidates[i] != last) {
list.add(candidates[i])
search(candidates, target - candidates[i], i + 1, list)
last = list.removeAt(list.lastIndex)
}
}
}
}