-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCombinationSum.java
More file actions
46 lines (40 loc) · 1.08 KB
/
CombinationSum.java
File metadata and controls
46 lines (40 loc) · 1.08 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
39
40
41
42
43
44
45
46
package combinationSum;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CombinationSum {
List<List<Integer>> result = new ArrayList<>();
int[] tmp = {};
public List<List<Integer>> combinationSum(int[] candidates, int target) {
this.tmp = candidates;
Arrays.sort(tmp);
backTrack(new ArrayList(), 0, target);
return this.result;
}
public void backTrack(List<Integer> cur, int from, int target){
if(target == 0){
List<Integer> list = new ArrayList<Integer>(cur);
result.add(list);
return;
}
else if(target < 0){
return;
}
else {
for(int i = from; i < tmp.length && tmp[i] <= target; i++){
cur.add(tmp[i]);
backTrack(cur, i, target-tmp[i]);
cur.remove(new Integer(tmp[i]));
}
}
}
public static void main(String[] args){
List<Integer> cur = new ArrayList<>();
cur.add(1);
cur.add(2);
List<Integer> list = new ArrayList<Integer>(cur);
for(int i = 0; i < list.size(); i++){
System.out.println(list.get(i));
}
}
}