细节
startIndex:在一个集合里构建树,需要标志此时到哪个数了;如果是两个集合里取数,那就不需要用startIndex了
i:表示数可以重复取用
i + 1:表示数不能重复取用
39. 组合总和
关键点1:主函数排序,调用backTracking,返回结果
关键点2:两个结束条件
关键点3:添加到path,求和,递归调用,回溯
class Solution {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates); // 先进行排序
backTracking(candidates,target,0,0);
return res;
}
public void backTracking(int[] candidates, int target,int sum,int startIndex){
// 结束条件
if(sum > target) return;
if(sum == target){
res.add(new LinkedList<>(path));
return;
}
// 单层循环逻辑
for(int i = startIndex; i < candidates.length; i++){
// 如果 sum + candidates[i] > target 就终止遍历,剪枝
if (sum + candidates[i] > target) break;
path.add(candidates[i]);
sum += candidates[i];
backTracking(candidates,target,sum,i);
path.removeLast();
sum -= candidates[i];
}
}
}
40.组合总和II
关键点1:主函数排序,新建used,用来判断是否回溯到层级了,调用backTracking,返回结果
关键点2:两个结束条件
关键点3:要进行层级去重,添加到path,求和,used[i]标记为1,递归调用,回溯
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
int[] used = new int[candidates.length];
backTracking(candidates,target,0,0,used);
return res;
}
public void backTracking(int[] candidates, int target,int sum,int startIndex,int[] used){
// 终止条件
if(sum > target) return;
if(sum == target){
res.add(new ArrayList<>(path));
return;
}
// 单层循环条件
for(int i = startIndex;i < candidates.length; i++){
// 去重,used[i - 1] == 0是关键
if(i>0 && candidates[i] == candidates[i - 1] && used[i - 1] == 0){
continue;
}
path.add(candidates[i]);
sum += candidates[i];
used[i] = 1;
backTracking(candidates,target,sum,i+1,used);
path.remove(path.size() - 1);
sum -= candidates[i];
used[i] = 0;
}
}
}
131.分割回文串
关键点1:主函数调用backTracking,返回结果
关键点2:结束条件 startIndex 是切割线,当切割线到终点了
关键点3:单层循环条件里去判断是否是回文串,是回文串才放入path里,不是则i跳下一个,递归调用,回溯
关键点4:判断是否是回文串,两个指针往中间走,判断两个指针的值是否相等
class Solution {
List<List<String>> res = new ArrayList<>();
List<String> path = new ArrayList<>();
public List<List<String>> partition(String s) {
backStracking(s,0);
return res;
}
public void backStracking(String s,int startIndex){
// 终止条件
if(startIndex >= s.length()){
res.add(new ArrayList<>(path));
return;
}
// 单层循环条件
for(int i = startIndex;i < s.length();i++){
// 判断是否是回文串
if(isPd(s,startIndex,i)){//是
String str = s.substring(startIndex, i + 1);
path.add(str);
}else{//不是
continue;
}
backStracking(s,i+1);
path.remove(path.size()-1);
}
}
public boolean isPd(String s,int left ,int right){
while(left < right){
if(s.charAt(left) != s.charAt(right)){
return false;
}
left++;
right--;
}
return true;
}
}