Skip to content

Commit 66b2ff2

Browse files
committed
39. Combination Sum
1 parent 8627a2c commit 66b2ff2

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

combination-sum/TonyKim9401.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution {
2+
// time complexity: O(2^n);
3+
// space complecity: O(n*m);
4+
private List<List<Integer>> output = new ArrayList<>();
5+
public List<List<Integer>> combinationSum(int[] candidates, int target) {
6+
backtracking(candidates, 0, target, new ArrayList<>());
7+
return output;
8+
}
9+
10+
public void backtracking(int[] candidates, int idx, int target, List<Integer> inside) {
11+
if (target == 0) {
12+
output.add(new ArrayList<>(inside));
13+
return;
14+
}
15+
16+
if (idx > candidates.length - 1 || target < 0) return;
17+
18+
inside.add(candidates[idx]);
19+
backtracking(candidates, idx, target - candidates[idx], inside);
20+
inside.remove(inside.size()-1);
21+
backtracking(candidates, idx+1, target, inside);
22+
}
23+
}

0 commit comments

Comments
 (0)