Day27 回溯 part03
我的思路:
类似于之前写过的216.组合综合III,只需要回溯时用一个sum控制,回溯i不是i+1,使得元素本身也可以取到即可
解答:
class Solution {
public List<List<Integer>> res = new ArrayList();
public List path = new ArrayList();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
if(candidates == null || candidates.length == 0) {
return new ArrayList();
}
backtracing(candidates, 0, 0, target);
return res;
}
public void backtracing(int[] candidates, int startindex, int sum, int target) {
if(sum == target) {
res.add(new ArrayList(path));
return;
}
if(sum > target) {
return;
}
for(int i = startindex; i < candidates.length; i++) {
path.add(candidates[i]);
backtracing(candidates, i, sum + candidates[i], target);
path.removeLast();
}
}
}
我的思路:
本来就只想在上一题基础上把i改回i+1,并且判断path在不在res里面的,但是有例子超时;
发现是需要对重复元素进行剪枝
解答:
class Solution {
public List<List<Integer>> res = new ArrayList();
public List path = new ArrayList();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
if(candidates == null || candidates.length == 0) {
return new ArrayList();
}
Arrays.sort(candidates);
backtracing(candidates, 0, target, 0);
return res;
}
public void backtracing(int[] candidates, int startIndex, int target, int sum) {
if(sum == target && ! res.contains(path)) {
res.add(new ArrayList(path));
return;
}
if(sum > target) {
return;
}
for(int i = startIndex; i < candidates.length; i++) {
if(i > startIndex && candidates[i] == candidates[i - 1]) {
continue;
}
path.add(candidates[i]);
backtracing(candidates, i+1, target, sum + candidates[i]);
path.removeLast();
}
}
}
我的思路:
在上题基础上,判断分割的子串,是否为回文的函数
解答:
class Solution {
public List<List<String>> res = new ArrayList();
public List<String> path = new ArrayList();
public List<List<String>> partition(String s) {
if(s == null || s.length() == 0) {
return new ArrayList();
}
backtracing(s, 0);
return res;
}
public void backtracing(String s, int startIndex) {
if(startIndex == s.length()) {
res.add(new ArrayList(path));
return;
}
for(int i = startIndex; i < s.length(); i++) {
if(isHuiwen(s, startIndex, i)) {
path.add(s.substring(startIndex, i + 1));
backtracing(s, i+1);
path.remove(path.size() - 1);
}
}
}
public boolean isHuiwen(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;
}
}