Day27
39.组合总和
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
backTracking(candidates, target,0, path, 0);
return res;
}
public void backTracking(int[] candidates,int target, int sum, List<Integer> path, int startIndex) {
if (sum > target) return;
if (sum == target) {
res.add(new ArrayList<>(path));
return;
}
for (int i = startIndex; i < candidates.length; i++) {
path.add(candidates[i]);
backTracking(candidates, target, sum + candidates[i], path, i);
path.remove(path.size() - 1);
}
}
}
40.组合总和Ⅱ
candidate含有重复数字,求组合总数需要先对候选数组进行排序再进行树层去重
使用标记数组
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
boolean used[];
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
used = new boolean[candidates.length];
backTracking(candidates, target, 0, 0);
return res;
}
public void backTracking (int[] candidates, int target, int startIndex, int sum) {
if (sum > target) return;
if (sum == target) {
res.add(new ArrayList<>(path));
return;
}
for (int i = startIndex; i < candidates.length; i++) {
if (i > 0 && candidates[i - 1] == candidates[i] && !used[i - 1]) {
continue;
}
path.add(candidates[i]);
used[i] = true;
backTracking(candidates,target, i + 1, sum + candidates[i]);
path.remove(path.size() - 1);
used[i] = false;
}
}
}
不使用标记数组
利用 i > startIndex 的条件,来保证是同一层的而非同一树枝
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
backTracking(candidates, target, 0, 0);
return res;
}
public void backTracking (int[] candidates, int target, int startIndex, int sum) {
if (sum > target) return;
if (sum == target) {
res.add(new ArrayList<>(path));
return;
}
for (int i = startIndex; i < candidates.length; i++) {
if (i > startIndex && candidates[i - 1] == candidates[i]) {
continue;
}
path.add(candidates[i]);
backTracking(candidates,target, i + 1, sum + candidates[i]);
path.remove(path.size() - 1);
}
}
}
131.分割回文串
class Solution {
List<List<String>> res = new ArrayList<>();
List<String> path = new ArrayList<>();
public List<List<String>> partition(String s) {
backTracking(0, s, path);
return res;
}
public void backTracking (int startIndex, String s, List<String> path) {
if (startIndex >= s.length()) {
res.add(new ArrayList<>(path));
return;
}
for (int i = startIndex; i < s.length(); i++) {
if (hui(s,startIndex,i)) {
path.add(s.substring(startIndex, i + 1));
} else continue;
backTracking(i + 1, s, path);
path.remove(path.size() - 1);
}
}
public boolean hui (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;
}
}