回溯3|39.组合总和| 40.组合总和II|131.分割回文串
一、39.组合总和
- 本题没有数量要求,可以无限重复,但是有总和的限制,所以间接的也是有个数的限制。
- 关键点:递归的时候不用 i+1了,从 i 开始,表示可以重复读取当前的数。
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
if(candidates.length == 0 ||candidates == null){
return result;
}
backtracking(candidates, target, 0, 0);
return result;
}
public void backtracking(int[] candidates, int target, int sum, int index){
if(sum > target){
return;
}
if(sum == target){
result.add(new ArrayList<>(path));
return;
}
for(int i = index; i < candidates.length; i++){
path.add(candidates[i]);
sum += candidates[i];
backtracking(candidates, target, sum, i);
sum -= candidates[i];
path.removeLast();
}
}
}
二、 40.组合总和II
题目连接:40. 组合总和 II - 力扣(LeetCode)
- 用数组used 标记candidates 中的元素是否被使用过。used[i - 1] == true,说明同一树枝candidates[i - 1]使用过;used[i - 1] == false,说明同一树层candidates[i - 1]使用过。
- 去重操作:先对candidates 数组进行排序,通过判断candidates[i] == candidates[i - 1] && !used[i - 1] 是否为真,若为真则收集的是重复的结果,需要跳过。
class Solution {
List<List<Integer>> reslut = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
boolean[] used;
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
used = new boolean[candidates.length];
Arrays.fill(used,false);
Arrays.sort(candidates);
backtracking(candidates, target, 0, 0);
return reslut;
}
public void backtracking(int[] candidates, int target, int sum, int index){
if(sum > target) return;
if(sum == target){
reslut.add(new ArrayList<>(path));
return;
}
for(int i = index; i < candidates.length; i++){
// used[i - 1] == true,说明同一树枝candidates[i - 1]使用过
// used[i - 1] == false,说明同一树层candidates[i - 1]使用过
if(i > 0 && candidates[i] == candidates[i - 1] && !used[i - 1]){
continue;
}
path.add(candidates[i]);
sum += candidates[i];
used[i] = true;
backtracking(candidates, target, sum, i + 1);
used[i] = false;
sum -= candidates[i];
path.removeLast();
}
}
}
三、131.分割回文串
题目连接:131. 分割回文串 - 力扣(LeetCode)
- 思路:与组合问题类似,递归用来纵向遍历,for循环用来横向遍历,切割线切割到字符串的结尾位置,说明找到了一个切割方法。
- 用 index 记录遍历到第几个字符了,因为切割过的地方,不能重复切割,和组合问题也是保持一致的。
class Solution {
List<List<String>> res = new ArrayList<>();
LinkedList<String> path = new LinkedList<>();
public List<List<String>> partition(String s) {
backtracking(s, 0);
return res;
}
public void backtracking(String s, int index){
// 如果起始位置已经大于s的大小,说明已经找到了一组分割方案了
if(index >= s.length()){
res.add(new ArrayList<>(path));
return;
}
for(int i = index; i < s.length(); i++){
if(isPartition(s, index, i)){
String str = s.substring(index, i + 1);//左闭右开
path.add(str);
}else {
continue;
}
backtracking(s, i + 1);
path.removeLast();
}
}
//判断是否为回文串
public boolean isPartition(String s, int start, int end){
for(int i = start, j = end; i < j; i++,j--){
if(s.charAt(i) != s.charAt(j)){
return false;
}
}
return true;
}
}