一、39. 组合总和
剪枝优化
以及上面的版本一的代码大家可以看到,对于sum已经大于target的情况,其实是依然进入了下一层递归,只是下一层递归结束判断的时候,会判断sum > target的话就返回。
其实如果已经知道下一层的sum会大于target,就没有必要进入下一层递归了。
那么可以在for循环的搜索范围上做做文章了。
对总集合排序之后,如果下一层的sum(就是本层的 sum + candidates[i])已经大于target,就可以结束本轮for循环的遍历。
for循环剪枝代码如下:
for (int i = startIndex; i < candidates.size() && sum + candidates[i] <= target; i++)
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
if(candidates == null || candidates.length == 0) {
return result;
}
Arrays.sort(candidates);
backTracking(candidates, target, 0, 0);
return result;
}
public 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++) {
sum += candidates[i];
path.add(candidates[i]);
backTracking(candidates, target, sum, i); // 不用i+1了,表示可以重复读取当前的数
sum -= candidates[i];
path.removeLast();
}
}
}
二、40.组合总和II
写着写着发现要去重了,要么传入的数组之前去重,要么在处理逻辑中去重。这里采用used数组。
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
boolean[] used;
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
if(candidates == null || candidates.length == 0) {
return result;
}
used = new boolean[candidates.length];
// 加标志数组,用来辅助判断同层节点是否已经遍历
Arrays.fill(used, false);
Arrays.sort(candidates);
backTracking(candidates, target, 0, 0);
return result;
}
public 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 ; i++) {
if (sum + candidates[i] > target) {
break;
}
// 出现重复节点,同层的第一个节点已经被访问过,所以直接跳过
if (i > 0 && candidates[i] == candidates[i - 1] && !used[i - 1]) {
continue;
}
used[i] = true;
sum += candidates[i];
path.add(candidates[i]);
backTracking(candidates, target, sum, i + 1);
used[i] = false;
path.removeLast();
sum -= candidates[i];
}
}
}
三、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;
}
public void backtracking(String s, int startIndex) {
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);
}
}
public 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;
}
}