-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathCombinationSum.java
30 lines (26 loc) · 1.05 KB
/
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
import java.util.*;
public class CombinationSum {
public static void main(String[] args) {
int[] candidates = {2,3,6,7};
System.out.println(combinationSum(candidates, 7));
}
public static List<List<Integer>> combinationSum(int[] candidates, int target) {
if(candidates.length == 0) return null;
List<List<Integer>> result = new ArrayList<>();
backTracking(candidates, target, 0, new ArrayList<>(), result);
return result;
}
public static void backTracking(int[] candidates, int target, int index, List<Integer> current, List<List<Integer>> result){
if(target == 0 ){
result.add(new ArrayList<>(current));
return;
}
for(int i = index ; i < candidates.length; i++){
if(target >= candidates[i]){
current.add(candidates[i]);
backTracking(candidates, target - candidates[i], i, current, result);
current.remove(Integer.valueOf(candidates[i]));
}
}
}
}