Skip to content

Commit ca3c33e

Browse files
committed
combination-sum solution
1 parent d2eb309 commit ca3c33e

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution {
2+
public List<List<Integer>> combinationSum(int[] candidates, int target) {
3+
List<List<Integer>> answer = new ArrayList<>();
4+
Arrays.sort(candidates); //๋ถˆํ•„์š”ํ•œ ํƒ์ƒ‰์„ ์ค„์ด๊ธฐ ์œ„ํ•ด sorting
5+
dfs(0, candidates, target, new ArrayList<>(), answer);
6+
return answer;
7+
8+
}
9+
10+
public void dfs(int start, int[] candidates, int target, List<Integer> curList, List<List<Integer>> answer) {
11+
if (target == 0) {
12+
answer.add(new ArrayList<>(curList));
13+
return;
14+
}
15+
for(int i = start; i < candidates.length; i++) {
16+
if (candidates[i] > target) {
17+
break;
18+
}
19+
20+
curList.add(candidates[i]);
21+
dfs(i, candidates, target - candidates[i], curList, answer);
22+
curList.remove(curList.size()-1); //๋‹ค์Œ ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ์œ„ํ•ด backtracking
23+
24+
}
25+
}
26+
}

0 commit comments

Comments
ย (0)