216.组合总和III
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
int sum=0;
backTracking(candidates, target, sum, 0);
return res;
}
public void backTracking(int[] candidates, int target, int sum, int index){
if(sum>target){
return;
}
if(sum == target){
res.add(new ArrayList<>(path));
return;
}
for(int i=index;i< candidates.length && sum + candidates[i] <= target;++i){
path.add(candidates[i]);
sum+=candidates[i];
backTracking(candidates, target, sum, i);
path.remove(path.size()-1);
sum-=candidates[i];
}
}
}
17.电话号码的字母组合
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
boolean[] used;
int sum=0;
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);
return res;
}
public void backTracking(int[] candidates, int target, int index){
if(sum == target){
res.add(new ArrayList<>(path));
return;
}
for(int i=index;i<candidates.length; ++i){
if (sum + candidates[i] > target) {
break;
}
if(i>0 && candidates[i] == candidates[i-1] && !used[i-1]) continue;
sum+=candidates[i];
used[i] = true;
path.add(candidates[i]);
backTracking(candidates, target, i+1);
path.remove(path.size()-1);
sum-=candidates[i];
used[i] = false;
}
}
}
131.分割回文串
class Solution {
List<List<String>> res = new ArrayList<>();
Deque<String> path = new LinkedList<>();
public List<List<String>> partition(String s) {
backTracing(s, 0);
return res;
}
public void backTracing(String s, int index){
if(index >= s.length()){
res.add(new ArrayList<>(path));
return;
}
for(int i=index;i<s.length(); i++){
if(isPalindrome(s, index, i)){
String str = s.substring(index, i+1);
path.addLast(str);
}else{
continue;
}
backTracing(s, i+1);
path.removeLast();
}
}
public boolean isPalindrome(String s, int index, int end){
for(int i=index, j=end; i<j; i++, j--){
if(s.charAt(i) != s.charAt(j)){
return false;
}
}
return true;
}
}