Skip to content

Commit 0f731bc

Browse files
committed
Add combination sum solution
1 parent ee4469d commit 0f731bc

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

combination-sum/hyunjung-choi.kt

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
class Solution {
2+
fun combinationSum(candidates: IntArray, target: Int): List<List<Int>> {
3+
val result = mutableListOf<List<Int>>()
4+
val currentCombination = mutableListOf<Int>()
5+
6+
candidates.sort()
7+
8+
backtrack(candidates, target, 0, currentCombination, result)
9+
10+
return result
11+
}
12+
13+
private fun backtrack(
14+
candidates: IntArray,
15+
remainingTarget: Int,
16+
startIndex: Int,
17+
currentCombination: MutableList<Int>,
18+
result: MutableList<List<Int>>
19+
) {
20+
if (remainingTarget == 0) {
21+
result.add(currentCombination.toList())
22+
return
23+
}
24+
25+
if (remainingTarget < 0) {
26+
return
27+
}
28+
29+
for (i in startIndex until candidates.size) {
30+
val candidate = candidates[i]
31+
32+
if (candidate > remainingTarget) {
33+
break
34+
}
35+
36+
currentCombination.add(candidate)
37+
38+
backtrack(candidates, remainingTarget - candidate, i, currentCombination, result)
39+
40+
currentCombination.removeAt(currentCombination.size - 1)
41+
}
42+
}
43+
}

0 commit comments

Comments
 (0)