public List<List<Integer>> combinationSum(int[] candidates, int target) {
ArrayList<List<Integer>> res = new ArrayList<>();
if (candidates == null || candidates.length == 0) {
return res;
}
// Arrays.sort(candidates);
backtracking(target, 0, candidates, new ArrayList<Integer>(), res);
return res;
}
private void backtracking(int target, int index, int[] nums, ArrayList<Integer> path, ArrayList<List<Integer>> res) {
if (target == 0) {
res.add(new ArrayList<Integer>(path));
return;
}
if (target < 0 || index >= nums.length) {
return;
}
for (int i = index; i < nums.length; i++) {
path.add(nums[i]);
// item 可以重复使用,故 next index 为 i
backtracking(target - nums[i], i, nums, path, res);
path.remove(path.size() - 1);
}
}
40. Combination Sum II 题目截图
public List<List<Integer>> combinationSum2(int[] nums, int target) {
ArrayList<List<Integer>> res = new ArrayList<>();
if (nums == null || nums.length == 0) {
return res;
}
Arrays.sort(nums);
backtracking(target, 0, nums, new ArrayList<Integer>(), res);
return res;
}
private void backtracking(int target, int index, int[] nums, ArrayList<Integer> path, ArrayList<List<Integer>> res) {
if (target == 0) {
res.add(new ArrayList<Integer>(path));
return;
}
if (target < 0 || index >= nums.length) {
return;
}
for (int i = index; i < nums.length; i++) {
// 该 for 循环,是对 current path next item 的尝试;
// 当 i>index 且nums[i] == nums[i - 1], 说明这个 item 对 current path next item 的尝试已经在之前完成过了,
// 就不需要,也不应该再尝试了。
if (i > index && nums[i] == nums[i - 1]) {
continue;
}
path.add(nums[i]);
backtracking(target - nums[i], i + 1, nums, path, res);
path.remove(path.size() - 1);
}
}
网友评论