题目
给定一个无重复元素的数组 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]
]
题解
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res=new ArrayList<>();
List<Integer> path=new ArrayList<>();
Arrays.sort(candidates);
dfs(candidates,target,res,path,0);
return res;
}
//参数:备选数组,目标数,结果集,过程集,深度
private void dfs(int[] candidates,int target,List<List<Integer>> res,List<Integer> path,int start){
if(target==0){
res.add(new ArrayList<Integer>(path));//为什么一定要添加一个新的list呢?原来的path不就已经是一个arraylist了吗?
return;
}
//从索引start开始遍历。结束条件有两个。一个是遍历到底时结束。另一个是剩余目标和大于当前数组值才遍历(剪枝)。这两个不能换位置,否则会索引溢出
for(int i=start;i<candidates.length&&target>=candidates[i];i++){
path.add(candidates[i]);
dfs(candidates,target-candidates[i],res,path,i);
//这层的数据处理完了,退回上一层
path.remove(path.size()-1);//list的长度是size
}
}
}
思路:
-
回溯算法。
-
回溯法和动态规划的不同:动态规划只评估出一个最优解就行了,适合评估出一个方案。回溯法遍历出所有的方案,时间复杂度较高。
-
回溯算法中注意设置状态变量:depth表示递归到第几层。布尔数组used,false表示未选择,true表示已选择。
-
若排列问题讲究顺序的使用used数组。若组合问题讲究顺序的使用begin变量。
-
做法:
1、先排序
2、定义结果集。回溯路径集。作为参数传递到递归方法中。返回结果集
3、递归方法:深度优先递归
4、结束条件。目标和==0时结束。添加到结果集中
5、否则遍历数组。从上一个递归遍历位置处开始遍历。同时结束条件还需要剪枝。剩余目标和大于当前数组值时结束。
6、当前元素添加到回溯集。递归调用。更新剩余目标和。当前遍历索引传入。
7、回溯
时间复杂度:O(n*n),空间复杂度:O(target)。最坏的情况是元素1遍历target次,和为target