-
-
Notifications
You must be signed in to change notification settings - Fork 609
/
Copy pathCombinationSum.java
45 lines (37 loc) · 1015 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
42
43
44
45
package problems.medium;
import java.util.ArrayList;
import java.util.List;
/**
* Created by sherxon on 6/3/17.
*/
public class CombinationSum {
public static void main(String[] args) {
System.out.println(combinationSum(new int[]{7, 6, 3, 2}, 7));
}
static public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> list = new ArrayList<>();
if (target == 0 || candidates.length == 0) {
return list;
}
List<Integer> l = new ArrayList<>();
go(candidates, target, target, list, l, 0);
return list;
}
private static void go(int[] candidates, int x, int target, List<List<Integer>> list,
List<Integer> l, int i) {
if (x < 0) {
return;
}
if (x == 0) {
list.add(l);
} else {
for (int j = 0; j < candidates.length; j++) {
int xx = x - candidates[j];
if (xx >= 0) {
l.add(candidates[j]);
go(candidates, xx, target, list, l, i);
}
}
}
}
}