39. Combination Sum
Tag BackTracing
Difficulty Medium
Link https://leetcode-cn.com/problems/combination-sum/
思路
这道题与77题n选k类似,只不过多了一个可以重复取数的条件,依然使用深度优先搜索遍历,画图可以使得我们看得更加直观。
假设candidates=[2,3,6.7], target=7
可以看到[2,2,3]
这一组符合条件,还有[7]
符合条件。那么就可以写出如下代码。
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
Deque<Integer> path = new ArrayDeque<>();
dfs(candidates, target, 0, path, res);
return res;
}
public void dfs(int[] candidates, int target, int begin, Deque<Integer> path, List<List<Integer>> res) {
// 退出条件 和 == target
if (target == 0) {
res.add(new ArrayList<>(path));
return;
}
else if (target < 0) {
return;
}
for (int i = begin; i < candidates.length; i++) {
path.add(candidates[i]);
// 因为可以重复提取元素,所以这里传入的begin依然是i
dfs(candidates, target - candidates[i], i, path, res);
path.removeLast();
}
}
}
其实通过图也可以看出,有大量的计算是无效的,比如在得到[2,2,3]
这个组合后,依然会去计算[2,2,6]
和[2,2,7]
以及更深的递归,这些都造成了浪费,所以需要进行剪枝。
如果对数组进行排序,那么在路径和达到target后,就知道再加上后面的数就会变为负数,不符合要求,可以剪枝,所以新的代码如下。
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(candidates);
Deque<Integer> path = new ArrayDeque<>();
dfs(candidates, target, 0, path, res);
return res;
}
public void dfs(int[] candidates, int target, int begin, Deque<Integer> path, List<List<Integer>> res) {
// 退出条件 因为小于0被剪枝,所以不需要再判断
if (target == 0) {
res.add(new ArrayList<>(path));
return;
}
for (int i = begin; i < candidates.length; i++) {
if (target - candidates[i] < 0) {
break;
}
path.add(candidates[i]);
dfs(candidates, target - candidates[i], i, path, res);
path.removeLast();
}
}
}