forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCombination Sum.java
More file actions
38 lines (31 loc) · 1.09 KB
/
Combination Sum.java
File metadata and controls
38 lines (31 loc) · 1.09 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
35
36
37
38
class Solution {
Set<List<Integer>> set;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
set = new HashSet<>();
Arrays.sort(candidates);
combinationSumHelper(candidates, 0, target, new ArrayList<>());
return new ArrayList<>(set);
}
private void combinationSumHelper(int[] candidates, int currVal, int target, List<Integer> list) {
if (currVal == target) {
set.add(new ArrayList<>(list));
return;
}
if (currVal > target) {
return;
}
for (int i = 0; i < candidates.length; i++) {
if (list.size() > 0 && list.get(list.size() - 1) > candidates[i]) {
continue;
}
// Choose
currVal += candidates[i];
list.add(candidates[i]);
// Explore
combinationSumHelper(candidates, currVal, target, list);
// Unchoose
list.remove(list.size() - 1);
currVal -= candidates[i];
}
}
}