-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path039_CombinationSum39.java
84 lines (66 loc) · 2.52 KB
/
039_CombinationSum39.java
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
class Solution {
List<List<Integer>> comb;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
comb = new ArrayList();
List<Integer> lt = new ArrayList();
findSum(lt, candidates, 0, target);
return comb;
}
private void findSum(List<Integer> sumList, int[] candidates, int beg, int target){
if(target == 0){
comb.add(sumList);
return;
}
if(beg == candidates.length){
return;
}
if(candidates[beg] <= target){
List<Integer> lst = new ArrayList();
lst.addAll(sumList);
lst.add(candidates[beg]);
findSum(lst, candidates, beg, target - candidates[beg]);
}
findSum(sumList, candidates, beg+1, target);
}
}
***************************************************************************************************
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> current = new ArrayList<>();
helperFunction(result, current, candidates, 0, target, 0);
return result;
}
public void helperFunction(List<List<Integer>> result, List<Integer> current, int [] candidates, int start, int target, int sum) {
if (sum > target)
return;
if (sum == target) {
result.add(new ArrayList<>(current));
return;
}
for (int i=start; i<candidates.length; i++) {
current.add(candidates[i]);
helperFunction(result, current, candidates, i, target, sum+candidates[i]);
current.remove(current.size()-1);
}
}
}
*************************************************************************************
class Solution {
List<List<Integer>> resultList = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
helper(candidates, target, 0, 0, new ArrayList<>());
return resultList;
}
private void helper(int[] candidates, int target, int index, int sum, List<Integer> list) {
if (sum > target) return;
if (sum == target) {
resultList.add(new ArrayList(list));
}
for (int i = index; i < candidates.length; i++) {
list.add(candidates[i]);
helper(candidates, target, i , sum + candidates[i], list);
list.remove(list.size() - 1);
}
}
}