今日任务
39. 组合总和
40.组合总和II
131.分割回文串
39. 组合总和
题目链接:. - 力扣(LeetCode)
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
int sum = 0;
Set<String> set = new HashSet<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
restrospective(candidates, target);
return result;
}
public void restrospective(int[] candidates, int target){
if (sum > target) { return; }
if (sum == target) {
List<Integer> temp = new ArrayList(path);
Collections.sort(temp);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < temp.size(); i++) {
sb.append(temp.get(i) + "+");
}
if (!set.contains(sb.toString())) {
set.add(sb.toString());
result.add(new ArrayList(path));
}
return;
}
for (int i = 0; i < candidates.length; i++) {
path.add(candidates[i]);
sum += candidates[i];
restrospective(candidates, target);
sum -= path.get(path.size() - 1);
path.remove(path.size() - 1);
}
return;
}
}
40.组合总和II
题目链接: . - 力扣(LeetCode)
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
backTracking(candidates, target, 0, 0);
return result.stream().distinct().collect(Collectors.toList());
}
public List<List<Integer>> result = new ArrayList<>();
public List<Integer> path = new ArrayList<>();
public void backTracking(int[] candidates, int target, int startIndex, int sum) {
if (sum == target) {
result.add(new ArrayList<>(path));
return;
}
for (int i = startIndex; i < candidates.length; i++) {
if (sum + candidates[i] > target) {
break;
}
//跳过同一层使用过的元素
if (i > startIndex && candidates[i] == candidates[i - 1]) {
continue;
}
path.add(candidates[i]);
sum += candidates[i];
backTracking(candidates, target, i + 1, sum);
sum -= path.get(path.size() - 1);
path.remove(path.size() - 1);
}
return;
}
}
131.分割回文串
题目链接: . - 力扣(LeetCode)
class Solution {
List<List<String>> result = new ArrayList<>();
List<String> path = new ArrayList<>();
public List<List<String>> partition(String s) {
retrospective(s, 0);
return result;
}
public void retrospective(String s, int startIndex) {
if (startIndex == s.length()) {
result.add(new ArrayList<>(path));
return;
}
for (int i = startIndex; i < s.length(); i++) {
if (palidrome(s, startIndex, i)) {
path.add(s.substring(startIndex, i + 1));
retrospective(s, i + 1);
path.remove(path.size() - 1);
}
}
return;
}
public boolean palidrome(String s, int start, int end) {
/*
* 左闭右闭
* */
int left = start;
int right = end;
while (left < right) {
if (s.charAt(left++) != s.charAt(right--)) {
return false;
}
}
return true;
}
}