1.组合总和
class Solution {
List<List<Integer>> res = new ArrayList();
Deque<Integer> path = new ArrayDeque<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
backtrack(candidates, 0, target, 0);
return res;
}
private void backtrack(int[] candidates, int startIndex, int target, int sum){
if (sum > target) {
return;
}
if (sum == target) {
res.add(new ArrayList<>(path));
return;
}
for (int i = startIndex; i < candidates.length; i++) {
sum += candidates[i];
path.add(candidates[i]);
backtrack(candidates, i, target, sum);// i + 1是不重复选取, 用i 重复选取
sum -= candidates[i];
path.removeLast();
}
}
}
剪枝优化
for (int i = startIndex; i < candidates.size() && sum + candidates[i] <= target; i++)
2.组合总和II
组合总和进行去重,原理是排序
import java.util.*;
class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates); // 关键:排序以处理重复元素
backtrack(candidates, target, 0, new ArrayList<>(), 0);
return res;
}
private void backtrack(int[] candidates, int target, int start, List<Integer> path, int sum) {
if (sum == target) {
res.add(new ArrayList<>(path));
return;
}
for (int i = start; i < candidates.length; i++) {
// 跳过同一层的重复元素,避免重复组合
if (i > start && candidates[i] == candidates[i - 1]) continue;
int currSum = sum + candidates[i];
if (currSum > target) break; // 剪枝:后续元素更大,无需继续
path.add(candidates[i]);
backtrack(candidates, target, i + 1, path, currSum); // i+1 确保每个元素只用一次
path.remove(path.size() - 1);
}
}
}
3.分割回文串
class Solution {
// 1.元素返回值,List<String>
// 2.s.length();
List<List<String>> res = new ArrayList<>();
Deque<String> path = new ArrayDeque<>();
public List<List<String>> partition(String s) {
backtrack(s, 0, new StringBuilder());
return res;
}
private void backtrack(String s, int startIndex, StringBuilder sb) {
if (startIndex >= s.length()) {
res.add(new ArrayList<>(path));
return;
}
for (int i = startIndex; i < s.length(); i++) {
sb.append(s.charAt(i));
if (check(sb)) {
path.add(sb.toString());
backtrack(s, i + 1, new StringBuilder());
path.removeLast();
}
}
}
private boolean check(StringBuilder sb) {
for (int i = 0; i < sb.length()/2; i++) {
if (sb.charAt(i) != sb.charAt(sb.length() - 1 - i))
return false;
}
return true;
}
}