题目
给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。其中candidates 中的数字可以无限制重复被选取。
解释
1.主要考察回溯算法,给出没有剪枝的解法
2.回溯的主要思想就是一个for循环和一个dfs。其中for循环的作用就是遍历每层的所有节点,dfs的作用就是分别对这些节点进行深度优先遍历
3.回溯算法就是穷举所有可能出现的结果,可以通过剪枝操作来把绝对不可能的方案排除掉,进行优化。
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res=new ArrayList<List<Integer>>();//存放结果集
Arrays.sort(candidates); //通过对数组进行排序,来解决重复解
int index=0;
if(candidates.length==0){
return res;
}
Deque<Integer> path=new ArrayDeque<Integer>();
dfs(candidates,index,target,path,res);//关键操作
return res;
}
void dfs(int [] candidates,int index,int target,Deque<Integer> path,List<List<Integer>> res){
if(target<0){ //当目标值小于0的时候不用再往下走了
return ;
}
if(target==0){ //当目标值为0时说明是一个正确解
res.add(new ArrayList(path));
return ;
}
for(int begin=index;begin<candidates.length;begin++){//通过for循环遍历来处理当前层的所有点
path.addLast(candidates[begin]); //将当前节点加入到路径中
dfs(candidates,begin,target-candidates[begin],path,res); //深度优先遍历这个节点,注意到题目说明数组candidates中的数可以重复使用,所以开始位置仍然是begin。由于刚才加上了当前节点,所以此时target的值变为了target-candidates[begin]
path.removeLast();//对当前节点进行dfs之后,把当前节点移出路径path,进行下一个节点的操作
}
}
}