Skip to content

Commit 2c5bf5f

Browse files
committed
feat : combination-sum
1 parent 9694699 commit 2c5bf5f

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

combination-sum/ekgns33.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import java.util.ArrayList;
2+
import java.util.List;
3+
4+
/**
5+
input : array of distinct integers, single integer target
6+
output : all unique combinations of candidates where chosen ones sum is target
7+
constraints:
8+
1) can we use same integer multiple times?
9+
yes
10+
2) input array can be empty?
11+
no. [1, 30]
12+
13+
14+
solution 1)
15+
combination >> back-tracking
16+
O(2^n) at most 2^30 << (2^10)^3 ~= 10^9
17+
18+
tc : O(2^n) sc : O(n) call stack
19+
*/
20+
class Solution {
21+
public List<List<Integer>> combinationSum(int[] candidates, int target) {
22+
List<List<Integer>> answer = new ArrayList<>();
23+
List<Integer> prev = new ArrayList<>();
24+
backTrackingHelper(answer, prev, candidates, target, 0, 0);
25+
return answer;
26+
}
27+
private void backTrackingHelper(List<List<Integer>> ans, List<Integer> prev, int[] cands, int target, int curSum, int p) {
28+
if(curSum == target) {
29+
ans.add(new ArrayList(prev));
30+
return;
31+
}
32+
if(p >= cands.length) return;
33+
34+
for(int i = p; i< cands.length; i++) {
35+
if((curSum + cands[i]) <= target) {
36+
prev.add(cands[i]);
37+
backTrackingHelper(ans, prev, cands, target, curSum + cands[i],i);
38+
prev.remove(prev.size() - 1);
39+
}
40+
}
41+
}
42+
}

0 commit comments

Comments
 (0)