代码实现:
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> path = new ArrayList<>();
backtracking(ans, path, candidates, target, 0, 0);
return ans;
}
void backtracking(List<List<Integer>> ans, List<Integer> path, int[] candidates, int target, int sum, int startIndex) {
if (sum > target) return;
if (sum == target) {
ans.add(new ArrayList<>(path));
return;
}
for (int i = startIndex; i < candidates.length; i++) {
path.add(candidates[i]);
backtracking(ans, path, candidates, target, sum + candidates[i], i);
path.remove(path.size() - 1);
}
}
}
代码实现:
class Solution {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> path = new ArrayList<>();
int sum = 0;
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
backtracking(ans, path, candidates, target, 0, 0);
return ans;
}
void backtracking(List<List<Integer>> ans, List<Integer> path, int[] candidates, int target, int sum, int startIndex) {
if (sum > target) return;
if (sum == target) {
ans.add(new ArrayList<>(path));
return;
}
for (int i = startIndex; i < candidates.length && sum + candidates[i] <= target; i++) {
if (i > startIndex && candidates[i] == candidates[i - 1]) continue;
sum += candidates[i];
path.add(candidates[i]);
backtracking(ans, path, candidates, target, sum, i + 1);
int temp = path.get(path.size() - 1);
sum -= temp;
path.remove(path.size() - 1);
}
}
}
题目:
代码实现:
class Solution {
List<List<String>> ans = new ArrayList<>();
List<String> path = new ArrayList<>();
public List<List<String>> partition(String s) {
backtracking(s, 0);
return ans;
}
void backtracking(String s, int startIndex) {
if (startIndex >= s.length()) {
ans.add(new ArrayList<>(path));
return;
}
for (int i = startIndex; i < s.length(); i++) {
if (isValid(s, startIndex, i)) {
String str = s.substring(startIndex, i + 1);
path.add(str);
} else {
continue;
}
backtracking(s, i + 1);
path.remove(path.size() - 1);
}
}
boolean isValid(String s, int startIndex, int end) {
for (int i = startIndex, j = end; i < j; i++, j--) {
if (s.charAt(i) != s.charAt(j)) return false;
}
return true;
}
}