组合总和
题目描述:
给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的数字可以无限制重复被选取。
说明:
1.所有数字(包括 target)都是正整数。
2.解集不能包含重复的组合。
提示:
1 <= candidates.length <= 30
1 <= candidates[i] <= 200
candidate 中的每个元素都是独一无二的。
1 <= target <= 500
class Solution {
private int[] candidates;
private List<List<Integer>> result;
private List<Integer> temp;
private int target;
private int len;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
// 回溯算法
// 初始化
this.candidates = candidates;
this.result = new ArrayList<List<Integer>>();
this.temp = new ArrayList<Integer>();
this.target = target;
this.len = candidates.length;
DFS(0,0); // 第一个参数为当前栈中的和 第二个参数(这里有坑,也是本题的唯一难点)主要是防止出现重合路径
return result;
}
public void DFS(int sum,int begin){
if(sum == this.target){
List<Integer> temp = new ArrayList<Integer>(); // 使用局部temp
for(int i = 0 ; i<this.temp.size() ; i++) temp.add(this.temp.get(i));
this.result.add(temp);
return;
}
if(sum > this.target){ // 剪枝操作
return;
}
for(int i = begin ; i<len ; i++){ // 从当前的位置begin开始遍历所有可能选到的元素
this.temp.add(candidates[i]);
DFS(sum+candidates[i],i);
this.temp.remove(temp.size() - 1); // 还原
}
}
}
典型的回溯算法,这里唯一的难点是,如何才能不产生元素内容相同的重复路径,这里通过每次从当前回溯位置来继续遍历来防止产生元素内容相同的重复路径,读者如果觉得有些抽象,可以通过纸上模拟理解。