题目:
给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的数字可以无限制重复被选取。
说明:
所有数字(包括 target)都是正整数。
解集不能包含重复的组合。
示例 1:
输入: candidates = [2,3,6,7], target = 7,
所求解集为:
[
[7],
[2,2,3]
]
示例 2:
输入: candidates = [2,3,5], target = 8,
所求解集为:
[
[2,2,2,2],
[2,3,3],
[3,5]
]
思路:
采用回溯法+剪枝(去掉不符条件的)
1. 简单理解一下回溯法,回溯算法实际上一个类似枚举的搜索尝试过程,主要是在搜索尝试过程中寻找问题的解,当发现已不满足求解条件时,就“回溯”返回,尝试别的路径。回溯法是一种选优搜索法,按选优条件向前搜索,以达到目标。但当探索到某一步时,发现原先选择并不优或达不到目标,就退回一步重新选择,这种走不通就退回再走的技术为回溯法,而满足回溯条件的某个状态的点称为“回溯点”。
2.解决一个回溯问题,实际上就是一个决策树的遍历过程。需要思考 3 个问题:
1、路径:也就是已经做出的选择。
2、选择列表:也就是你当前可以做的选择。
3、结束条件:也就是到达决策树底层,无法再做选择的条件。
代码方面,回溯算法的框架:
res = []
def backtrack(路径, 选择列表):
if 满足结束条件:
res.add(路径)
return
for 选择 in 选择列表:
做选择
backtrack(路径, 选择列表)
撤销选择
其核心就是 for 循环里面的递归,在递归调用之前「做选择」,在递归调用之后「撤销选择」
先选择,发现满足中断条件的,就可以退出来,并撤销选择。
3. 结合题目:我们需要数组candidaties[2,3,6,7]里的能够组合的和是7的数字组合,也就是路径【】,并且路径元素组合是不重复的【2,3,2】和【2,2,3】就是重复的。
所以,要过滤掉【2,3,2】这种情况:
1.对数组进行从小到大排序【2,3,6,7】
Arrays.sort(candidates);
2.对【2,3,6,7】进行不断的组合
选择结束条件,以及组合方式
组合方式 令target=target-candidates[i] 就是7-candidates[i]不断减下去
for (int i = level; i < candidates.length; i++) {
result.add(candidates[i]);
dfs(candidates, results, result, i, target - candidates[i]);
result.remove(result.size()-1);
}
结束条件
target<0时说明走不通,路径倒回去,target==0时,说明一个路径走通了,存下来这个路径,找下一个i
if (target < 0) return;
if (target == 0) {
results.add(new ArrayList(result));
return;
注释:这里为什么要用new ArrayList(result)??因为<List<Integer>这个对象是引用类型,如果不新建一个对象放result,result
一旦最后一步找不到解,结果就是空的,类似于几个人住房子,一个result住一个房子,不new的话,一个来了,另一个就要被挤掉。
全部代码如下:
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> results = new ArrayList<>();
List<Integer> result = new ArrayList<>();
Arrays.sort(candidates);
dfs(candidates, results, result, 0, target);
return results;
}
private void dfs(int[] candidates, List<List<Integer>> results, List<Integer> result, int level, int target) {
//剪枝
if (target < 0) return;
//找到合适的路径
if (target == 0) {
results.add(result);
return;
} else {
for (int i = level; i < candidates.length; i++) {
result.add(candidates[i]);
dfs(candidates, results, result, i, target - candidates[i]);
result.remove(result.size()-1);
}
}
}
}