39. 组合总和
class Solution {
private List<List<Integer>> result = new ArrayList<>();
private List<Integer>path = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates); // 排序后可以进行后面的剪枝
backTracking(candidates,target,0);
return result;
}
private void backTracking(int []candidates,int target,int startIndex){
if(target == 0){
result.add(new ArrayList(path));
return;
}
for(int i = startIndex; i < candidates.length;i++){
if(target - candidates[i] < 0)break;//此处剪枝是排序作为前提的
path.add(candidates[i]);
backTracking(candidates,target - candidates[i],i);
path.remove(path.size() - 1);
}
}
}
40.组合总和II
Arrays.fill(used, false);//合理的初始化
class Solution {
private List<List<Integer>> result = new ArrayList<>();
private List<Integer>path = new ArrayList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
boolean[] used = new boolean[candidates.length];
backTracking(candidates,target,0,used);
return result;
}
private void backTracking(int[]candidates,int target,int startIndex,boolean[]used){
if(target == 0){
result.add(new ArrayList(path));
return;
}
for(int i = startIndex;i < candidates.length;i++){
if(target - candidates[i] < 0)break;
if(i != 0 && candidates[i] == candidates[i-1] && used[i - 1] == false)continue;
used[i] = true;
path.add(candidates[i]);
backTracking(candidates,target - candidates[i],i + 1,used);
path.remove(path.size() - 1);
used[i] = false;
}
}
}
131.分割回文串
class Solution {
private List<List<String>>result = new ArrayList<>();
private Deque<String> path = new LinkedList<>();
public List<List<String>> partition(String s) {
backTracking(s,0);
return result;
}
private void backTracking(String s,int startIndex){
if(startIndex > s.length() - 1){
result.add(new ArrayList(path));
return;
}
for(int i = startIndex;i < s.length();i++){
String subStr = s.substring(startIndex,i + 1);
if(isPalindrome(subStr)){
path.addLast(subStr);
}
else continue;
backTracking(s,i + 1);
path.removeLast();
}
}
private boolean isPalindrome(String str){
int left = 0;
int right = str.length() - 1;
while(left <= right){
if(str.charAt(left) != str.charAt(right))return false;
left++;
right--;
}
return true;
}
}