代码随想录刷题Day27 | 39. 组合总和 | 40. 组合总和 II | 131. 分割回文串
39. 组合总和
题目:
给你一个 无重复元素 的整数数组 candidates
和一个目标整数 target
,找出 candidates
中可以使数字和为目标数 target
的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates
中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target
的不同组合数少于 150
个。
思路:
这道题中所有的数字可以重复使用,那么我们的返回条件就不再是数字个数,而是要通过和大小来判断,我们使用sum来记录当前路径的和,当和大于target时,证明此路不同,return去下一条路。
代码:
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
int sum = 0;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
backTracking(candidates, target, 0);
return result;
}
public void backTracking(int[] candidates, int target, int start){
if(sum == target){
result.add(new ArrayList<>(path));
return;
}
if(sum > target) return;
for(int i = start; i < candidates.length; i++){
path.add(candidates[i]);
sum += candidates[i];
backTracking(candidates, target, i);
path.remove(path.size() - 1);
sum -= candidates[i];
}
}
}
40. 组合总和 II
题目:
给定一个候选人编号的集合 candidates
和一个目标数 target
,找出 candidates
中所有可以使数字和为 target
的组合。
candidates
中的每个数字在每个组合中只能使用 一次 。
**注意:**解集不能包含重复的组合。
思路:
给定的candidates中有重复的数值,因此如果采用和上体一样的算法会出现重复的结果。本题的重点时如何去重,我们首先对candidates排序,然后再for循环中判断当前遍历到的元素是否和本轮中的上一个元素相等,也就是判断是否遍历过该元素,如果已经遍历过了,直接遍历下一个元素。
代码:
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
int sum = 0;
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
backTracking(candidates, target, 0);
return result;
}
public void backTracking(int[] candidates, int target, int start){
if(sum == target){
result.add(new ArrayList<>(path));
return;
}else if(sum > target) return;
for(int i = start; i < candidates.length; i++){
if(i > start && candidates[i] == candidates[i - 1]) continue;
path.add(candidates[i]);
sum += candidates[i];
backTracking(candidates, target, i + 1);
path.remove(path.size() - 1);
sum -= candidates[i];
}
}
}
131. 分割回文串
题目:
给你一个字符串 s
,请你将 s
分割成一些子串,使每个子串都是 回文串 。返回 s
所有可能的分割方案。
回文串 是正着读和反着读都一样的字符串。
思路:
首先定义一个函数判断字符串是否为回文串(使用双指针的方法)。递归用来纵向遍历,for循环用来横向遍历,切割线(就是图中的红线)切割到字符串的结尾位置,说明找到了一个切割方法。
代码:
class Solution {
List<List<String>> result = new ArrayList<>();
List<String> path = new ArrayList<>();
public List<List<String>> partition(String s) {
backTracking(s, 0);
return result;
}
public void backTracking(String s, int start){
if(start >= s.length()){
result.add(new ArrayList<>(path));
}
for(int i = start; i < s.length(); i++){
if(isPalindrome(s.substring(start, i + 1))){
path.add(s.substring(start, i + 1));
backTracking(s, i + 1);
path.remove(path.size() - 1);
}else{
continue;
}
}
}
public boolean isPalindrome(String s){
int l = 0, r = s.length() - 1;
while(l <= r){
if(s.charAt(l) != s.charAt(r)) return false;
l++;
r--;
}
return true;
}
}