Leetcode 39. 组合总和
题目链接
思路:回溯算法
代码:
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
// 剪枝操作:先进行排序,然后在for循环里面进行剪枝
Arrays.sort(candidates);
backtracking(candidates, target, 0, 0);
return result;
}
private void backtracking(int[] candidates, int target, int sum, int startIndex) {
// 确定终止条件
if (sum > target) {
return;
}
if (sum == target) {
result.add(new ArrayList<>(path));
return;
}
// 单层搜索逻辑
// 剪枝操作
for (int i = startIndex; i < candidates.length && sum + candidates[i] <= target; i++) {
path.add(candidates[i]);
sum += candidates[i];
backtracking(candidates, target, sum, i);
sum -= candidates[i];
path.remove(path.size() - 1);
}
}
}
Leetcode 40.组合总和II
题目链接
思路:回溯算法,去重
代码:
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
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, used);
return result;
}
private void backtracking(int[] candidates, int target, int sum, int startIndex, boolean[] used) {
// 确定终止条件
if (sum > target) {
return;
}
if (sum == target) {
result.add(new ArrayList<>(path));
return;
}
for (int i = startIndex; i < candidates.length; i++) {
// 去重
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);
// 回溯
path.remove(path.size() - 1);
sum -= candidates[i];
used[i] = false;
}
}
}
Leetcode 131.分割回文串
题目链接
思路:回溯算法
代码:
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;
}
private void backtracking(String s, int startIndex) {
//如果起始位置大于s的大小,说明找到了一组分割方案
if (startIndex >= s.length()) {
result.add(new ArrayList<>(path));
return;
}
for (int i = startIndex; i < s.length(); i++) {
//如果是回文子串,则记录
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);
}
}
// 判断是否是回文串
private boolean isPalindrome(String s, int startIndex, int end) {
for (int i = startIndex, j = end; i < j; i++, j--) {
if (s.charAt(i) != s.charAt(j)) {
return false;
}
}
return true;
}
}