学习目标:
- 39. 组合总和
- 40.组合总和II
- 131.分割回文串
学习内容:
39. 组合总和
题目链接&&文章讲解
给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target 的不同组合数少于 150 个。
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
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 ArrayList<>(path));
return;
}
for(int i = startIndex; i < candidates.length; i++){
path.add(candidates[i]);
sum = sum + candidates[i];
//同一个数字可以被重复选取,startIndex = i
backtracking(candidates, target, sum, i);
sum = sum - candidates[i];
path.remove(path.size() - 1);
}
}
}
40.组合总和II
题目链接&&文章讲解
给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用 一次 。
注意:解集不能包含重复的组合。
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];
Arrays.fill(used, 0);
backtraing(candidates, target, 0, used, 0);
return res;
}
public void backtraing(int[] candidates, int target, int sum, int[] used, int startIndex){
//终止条件
if(sum > target) return;
if(sum == target) {
res.add(new ArrayList<>(path));
return;
}
//处理逻辑
for(int i = startIndex; i < candidates.length; i++){
//树层去重
if(i > 0 && candidates[i] == candidates[i - 1] && used[i-1] == 0) continue;
//递归
path.add(candidates[i]);
sum = sum + candidates[i];
used[i] = 1;
backtraing(candidates, target, sum, used, i + 1);
//回溯
path.remove(path.size() - 1);
sum = sum - candidates[i];
used[i] = 0;
}
}
}
131.分割回文串
题目链接&&文章讲解
给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。
回文串 是正着读和反着读都一样的字符串。
class Solution {
List<List<String>> res = new ArrayList<>();
List<String> path = new ArrayList<>();
public List<List<String>> partition(String s) {
backtracking(s, 0);
return res;
}
public void backtracking(String s, int startIndex){
//终止条件:起始位置大于s的大小
if(startIndex == s.length()){
res.add(new ArrayList(path));
return;
}
//处理逻辑
for(int i = startIndex; i < s.length(); i++){
//如果是回文子串则加入path
if(isPalindrome(s, startIndex, i)){
String str = s.substring(startIndex, i + 1);
path.add(str);
}else continue;
backtracking(s, i + 1);
path.remove(path.size() - 1);
}
}
//双指针法: 判断是否为回文子串 左闭右闭区间[start,end]
public boolean isPalindrome(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;
}
}