39. 组合总和
class Solution {
List<List<Integer>> ans = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
backtrack(candidates, target, 0, 0, new ArrayList<>());
return ans;
}
private void backtrack(int[] candidates, int target,int index,int sum,List<Integer> list) {
if(target < sum) {
return;
}else if(target == sum) {
ans.add(new ArrayList<>(list));
return;
}else {
for(int i = index; i < candidates.length; ++i) {
list.add(candidates[i]);
sum += candidates[i];
backtrack(candidates, target, i, sum, list);
sum -= list.getLast();
list.remove(list.size()-1);
}
}
}
}
40.组合总和II
题目链接:40. 组合总和 II - 力扣(LeetCode)
class Solution {
List<List<Integer>> ans = new ArrayList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
int[] used = new int[candidates.length];
Arrays.sort(candidates);
backtrack(candidates, target, 0, 0, new ArrayList<>(),used);
return ans;
}
private void backtrack(int[] candidates,int target,int index,int sum,List<Integer> list,int[] used) {
if(sum > target) {
return;
}else if(sum == target) {
ans.add(new ArrayList<>(list));
}
for(int i = index; i < candidates.length; ++i) {
if(i > 0 && used[i - 1] == 0 && candidates[i] == candidates[i-1]) {
continue;
}
list.add(candidates[i]);
used[i] = 1;
sum += candidates[i];
backtrack(candidates, target, i+1, sum, list, used);
sum -= list.getLast();
list.remove(list.size()-1);
used[i] = 0;
}
}
}
131.分割回文串
题目链接:131. 分割回文串 - 力扣(LeetCode)
class Solution {
List<List<String>> ans = new ArrayList<>();
List<String> list = new ArrayList<>();
public List<List<String>> partition(String s) {
backtrack(s, 0);
return ans;
}
private void backtrack(String s,int index) {
if(index == s.length()) {
ans.add(new ArrayList<>(list));
return;
}
for(int i = index; i < s.length(); ++i) {
if(helper(s.substring(index, i + 1))) {
list.add(s.substring(index, i + 1));
}else {
continue;
}
backtrack(s, i + 1);
list.removeLast();
}
}
private boolean helper(String str) {
for(int i = 0, j = str.length() - 1; i < j; ++i,--j) {
if(str.charAt(i) != str.charAt(j)) {
return false;
}
}
return true;
}
}