LeeCode打卡第三十二天
第一题:组合总和II(LeeCode第40题):
给定一个候选人编号的集合 candidates
和一个目标数 target
,找出 candidates
中所有可以使数字和为 target
的组合。candidates
中的每个数字在每个组合中只能使用 一次 。**注意:**解集不能包含重复的组合。
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
backTracking(candidates, target, 0);
return res;
}
public void backTracking(int[] candidates, int target, int startIndex){
int sum = 0;
for(int n : temp) sum += n;
if(sum > target){
return;
}
if(sum == target){
res.add(new ArrayList<>(temp));
return;
}
for(int i = startIndex; i < candidates.length; i++){
if(i > startIndex && candidates[i] == candidates[i - 1]) continue;
temp.add(candidates[i]);
backTracking(candidates, target, i + 1);
temp.remove(temp.size() - 1);
}
}
}
第二题:分割回文串(LeeCode第131题):
给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是回文串。返回 s 所有可能的分割方案。。
主要思路:就是i注意回文子串的拼接,这里主要是用了StringBuilder的append方法实现的,再就是回文子串的判断,可以另写一个函数
class Solution {
List<List<String>> res = new ArrayList<>();
List<String> temp = new ArrayList<>();
public List<List<String>> partition(String s) {
backtracking(s, 0, new StringBuilder());
return res;
}
void backtracking(String s, int startIndex, StringBuilder sb){
if(startIndex == s.length()){
res.add(new ArrayList<>(temp));
return;
}
for(int i = startIndex; i < s.length(); i++){
sb.append(s.charAt(i));
if(check(sb)){
temp.add(sb.toString());
backtracking(s, i + 1, new StringBuilder());
temp.remove(temp.size() - 1);
}
}
}
private boolean check(StringBuilder sb){
for(int i = 0; i < sb.length()/2; i++){
if(sb.charAt(i) != sb.charAt(sb.length() - i - 1)) return false;
}
return true;
}
}