LeetCode39 组合总和
题目链接:https://programmercarl.com/0039.%E7%BB%84%E5%90%88%E6%80%BB%E5%92%8C.html
代码:
public class code39 {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
combination(candidates, target, 0, 0);
return res;
}
private void combination(int[] candidates, int target, int startIndex, int curTarget) {
// 剪枝
if (curTarget > target) {
return;
}
if (curTarget == target) {
res.add(new ArrayList<>(path));
return;
}
for (int i = startIndex; i < candidates.length; i++) {
path.add(candidates[i]);
curTarget += candidates[i];
combination(candidates, target, i, curTarget);
path.removeLast(); // 回溯
curTarget -= candidates[i]; // 回溯
}
}
}
LeetCode40 组合总和II
题目链接:https://programmercarl.com/0040.%E7%BB%84%E5%90%88%E6%80%BB%E5%92%8CII.html
代码:
public class code40 {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
combination(candidates, target, 0, 0);
return res;
}
private void combination(int[] candidates, int target, int startIndex, int curTarget) {
// 剪枝
if (curTarget > target) {
return;
}
if (curTarget == target) {
res.add(new ArrayList<>(path));
return;
}
for (int i = startIndex; i < candidates.length; i++) {
// 去重操作
if (i > startIndex && candidates[i] == candidates[i - 1]) {
continue;
}
path.add(candidates[i]);
curTarget += candidates[i];
combination(candidates, target, i + 1, curTarget);
path.removeLast(); // 回溯
curTarget -= candidates[i]; // 回溯
}
}
}
去重操作很精彩,注意区分树层去重和树枝去重
LeetCode131 分割回文串
题目链接:https://programmercarl.com/0131.%E5%88%86%E5%89%B2%E5%9B%9E%E6%96%87%E4%B8%B2.html
代码:
public class code131 {
List<List<String>> res = new ArrayList<>();
LinkedList<String> path = new LinkedList<>();
public List<List<String>> partition(String s) {
findRes(s, 0);
return res;
}
private void findRes(String s, int startIndex) {
// 收割结果
if (startIndex == s.length()) {
res.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;
}
findRes(s, i + 1);
path.removeLast(); // 回溯
}
}
// 判断是否是回文串
private 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;
}
}