Skip to content

Commit 7ebeef1

Browse files
committed
Add combination sum solution - s0ooo0k
1 parent b448877 commit 7ebeef1

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

combination-sum/s0ooo0k.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution {
2+
List<List<Integer>> result = new ArrayList<>();
3+
int[] candidates;
4+
5+
public List<List<Integer>> combinationSum(int[] candidates, int target) {
6+
this.candidates=candidates;
7+
backtrack(new ArrayList<>(), target, 0);
8+
return result;
9+
}
10+
void backtrack(List<Integer> comb, int remain, int start) {
11+
if(remain==0) {
12+
result.add(new ArrayList<>(comb));
13+
return;
14+
}
15+
if(remain<0) return;
16+
for(int i=start; i<candidates.length; i++) {
17+
comb.add(candidates[i]);
18+
backtrack(comb, remain-candidates[i], i);
19+
comb.remove(comb.size() - 1);
20+
}
21+
}
22+
}
23+

0 commit comments

Comments
 (0)