Skip to content

Commit 4b30789

Browse files
MEDIUM/src/medium/CombinationSum.java
1 parent 050fcee commit 4b30789

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

‎MEDIUM/src/medium/CombinationSum.java

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package medium;
2+
3+
import java.util.*;
4+
5+
import utils.CommonUtils;
6+
7+
public class CombinationSum {
8+
9+
public List<List<Integer>> combinationSum(int[] candidates, int target) {
10+
List<List<Integer>> result = new ArrayList();
11+
Arrays.sort(candidates);
12+
helper(candidates, target, 0, new ArrayList(), result);
13+
return result;
14+
}
15+
16+
private void helper(int[] candidates, int target, int startIndex, List<Integer> curr, List<List<Integer>> result){
17+
if(target > 0){
18+
for(int i = startIndex; i < candidates.length; i++){
19+
curr.add(candidates[i]);
20+
helper(candidates, target-candidates[i], i, curr, result);
21+
curr.remove(curr.size()-1);
22+
}
23+
} else if(target == 0){
24+
List<Integer> list = new ArrayList(curr);
25+
result.add(list);
26+
}
27+
}
28+
29+
30+
public static void main(String...args){
31+
CombinationSum test = new CombinationSum();
32+
int[] candidates = new int[]{2,3,6,7};
33+
int target = 7;
34+
List<List<Integer>> result = test.combinationSum(candidates, target);
35+
CommonUtils.printIntegerList(result);
36+
}
37+
38+
}

0 commit comments

Comments
 (0)