-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCombinationSum.java
More file actions
34 lines (28 loc) · 1.05 KB
/
Copy pathCombinationSum.java
File metadata and controls
34 lines (28 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CombinationSum {
}
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> answer = new ArrayList<>();
helper(candidates, target, new ArrayList<>(), 0,0, answer);
return answer;
}
public void helper(int[] candidates, int target, List<Integer> curNums, int curIndex, int curSum, List<List<Integer>> answer) {
if (curSum == target) {
answer.add(new ArrayList<>(curNums));
return;
}
if (curIndex == candidates.length || curSum + candidates[curIndex] > target) {
return;
}
curNums.add(candidates[curIndex]);
curSum += candidates[curIndex];
helper(candidates, target, curNums, curIndex, curSum, answer);
curNums.remove(curNums.size()-1);
curSum -= candidates[curIndex];
helper(candidates, target, curNums, curIndex+1, curSum, answer);
}
}