-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCombinationSum.java
More file actions
40 lines (30 loc) · 1.03 KB
/
CombinationSum.java
File metadata and controls
40 lines (30 loc) · 1.03 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
import java.util.*;
public class CombinationSum {
public static void main(String[] args) {
int[] candidates = {2, 3, 5, 7};
int target = 7;
List<List<Integer>> result = combinationSum(candidates, target);
System.out.println(result);
}
public static List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> ans = new ArrayList<>();
solve(candidates, target, 0, new ArrayList<>(), ans);
return ans;
}
public static void solve(int[] arr, int target, int index,
List<Integer> list, List<List<Integer>> ans) {
if (target == 0) {
ans.add(new ArrayList<>(list));
return;
}
if (target < 0 || index == arr.length) {
return;
}
// Choose
list.add(arr[index]);
solve(arr, target - arr[index], index, list, ans);
// Not Choose
list.remove(list.size() - 1);
solve(arr, target, index + 1, list, ans);
}
}