-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCombinationTargetSum.java
35 lines (30 loc) · 991 Bytes
/
CombinationTargetSum.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
import java.util.ArrayList;
import java.util.List;
public class CombinationTargetSum {
@SuppressWarnings({ "unchecked", "rawtypes" })
public List<List<Integer>> combinationSum(int[] nums, int target) {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
List<Integer> cur = new ArrayList();
backtrack(nums, target, ans, cur, 0);
return ans;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public void backtrack(
int[] nums,
int target,
List<List<Integer>> ans,
List<Integer> cur,
int index
) {
if (target == 0) {
ans.add(new ArrayList(cur));
} else if (target < 0 || index >= nums.length) {
return;
} else {
cur.add(nums[index]);
backtrack(nums, target - nums[index], ans, cur, index);
cur.remove(cur.get(cur.size() - 1));
backtrack(nums, target, ans, cur, index + 1);
}
}
}