Skip to content

Commit 5a8b85e

Browse files
committed
combination sum solved
1 parent 024836a commit 5a8b85e

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

combination-sum/mintheon.java

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import java.util.ArrayDeque;
2+
import java.util.ArrayList;
3+
import java.util.Deque;
4+
import java.util.List;
5+
6+
class Solution {
7+
/**
8+
시간복잡도: O(2^n)
9+
공간복잡도: O(n)
10+
*/
11+
public List<List<Integer>> combinationSum(int[] candidates, int target) {
12+
List<List<Integer>> answer = new ArrayList<>();
13+
Deque<Integer> nums = new ArrayDeque<>();
14+
15+
backtracking(candidates, answer, nums, target, 0, 0);
16+
17+
return answer;
18+
}
19+
20+
protected void backtracking(int[] candidates, List<List<Integer>> answer, Deque<Integer> nums, int target, int start, int total) {
21+
if(total > target) {
22+
return;
23+
}
24+
25+
if (total == target) {
26+
answer.add(new ArrayList<>(nums));
27+
return;
28+
}
29+
30+
for(int i = start; i < candidates.length; i++) {
31+
int num = candidates[i];
32+
nums.push(num);
33+
34+
backtracking(candidates, answer, nums, target, i, total + num);
35+
nums.pop();
36+
}
37+
}
38+
}

0 commit comments

Comments
 (0)