代码随想录算法训练营二十七天 第七章 | 39. 组合总和 40.组合总和II 131.分割回文串
39. 组合总和
class Solution {
private List<List<Integer>> result = new ArrayList<>();
private LinkedList<Integer> paths = new LinkedList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
if (candidates.length == 0) {
return result;
}
test(candidates, target, 0, 0);
return result;
}
public void test(int[] candidates, int target, int sum, int startIndex) {
if (sum > target) {
return;
}
if (sum == target) {
result.add(new ArrayList<>(paths));
return;
}
for (int i = startIndex; i < candidates.length; i++){
paths.add(candidates[i]);
sum += candidates[i];
test(candidates, target, sum, i);
sum -= candidates[i];
paths.removeLast();
}
}
}
40.组合总和II
class Solution {
public List<List<Integer>> result = new ArrayList<>();
public LinkedList<Integer> paths = new LinkedList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
test(candidates, target, 0, 0);
return result;
}
public void test(int[] candidates, int target, int sum, int startIndex) {
if (sum == target) {
result.add(new ArrayList<>(paths));
return;
}
for (int i = startIndex; i < candidates.length && sum + candidates[i] <= target; i++) {
if (i > startIndex && candidates[i] == candidates[i - 1]) {
continue;
}
paths.add(candidates[i]);
sum += candidates[i];
test(candidates, target, sum, i + 1);
sum -= candidates[i];
paths.removeLast();
}
}
}
131.分割回文串
class Solution {
public List<List<String>> result = new ArrayList<>();
public LinkedList<String> paths = new LinkedList<>();
public List<List<String>> partition(String s) {
test(s, 0);
return result;
}
public void test(String s, int startIndex) {
if (startIndex >= s.length()) {
result.add(new ArrayList<>(paths));
return;
}
for (int i = startIndex; i < s.length(); i++) {
if (ishuiwen(s, startIndex, i)) {
paths.add(s.substring(startIndex, i+1));
} else {
continue;
}
test(s, i+1);
paths.removeLast();
}
}
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;
}
}