-
Notifications
You must be signed in to change notification settings - Fork 6
/
CombinationSum.java
41 lines (29 loc) · 981 Bytes
/
CombinationSum.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
import java.util.*;
/**
* Created by abc on 17/01/2016.
*/
public class CombinationSum {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(candidates);
List<Integer> items = new ArrayList<>();
depthFirstSearch(candidates,result,items,0,target);
return result;
}
private void depthFirstSearch(int[] candidates,List<List<Integer>> result,List<Integer> items , int start, int target){
if(target < 0){
return;
}
if(target == 0){
result.add(new ArrayList<Integer>(items));
return;
}
for (int i = start; i <candidates.length ; i++) {
items.add(candidates[i]);
depthFirstSearch(candidates,result,items,i,target-candidates[i]);
items.remove(items.size()-1);
}
}
public static void main(String[] args) {
}
}