Skip to content

Commit 9608bb4

Browse files
committed
Solution for Combination Sum #254
1 parent d3c9c58 commit 9608bb4

1 file changed

Lines changed: 30 additions & 0 deletions

File tree

combination-sum/dohyeon2.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import java.util.ArrayList;
2+
import java.util.List;
3+
4+
class Solution {
5+
// TC : O(n!) => TC : O(2^T)
6+
// SC : O(n^2) => SC : O(T)
7+
ArrayList<List<Integer>> result = new ArrayList<>();
8+
9+
public List<List<Integer>> combinationSum(int[] candidates, int target) {
10+
backtrack(0, target, candidates, new ArrayList<>());
11+
return result;
12+
}
13+
14+
private void backtrack(int start, int diff, int[] candidates, ArrayList<Integer> path) {
15+
if (diff == 0) {
16+
result.add(new ArrayList<>(path)); // 깊은 복사
17+
return;
18+
}
19+
20+
if (diff < 0) {
21+
return;
22+
}
23+
24+
for (int i = start; i < candidates.length; i++) {
25+
path.add(candidates[i]);
26+
backtrack(i, diff - candidates[i], candidates, path);
27+
path.remove(path.size() - 1);
28+
}
29+
}
30+
}

0 commit comments

Comments
 (0)