class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> path = new ArrayList<>();
dfs(0, target, candidates, ans, path);
return ans;
}
public void dfs(int i, int left, int[] candidates, List<List<Integer>> ans, List<Integer> path) {
if (left == 0) {
ans.add(new ArrayList<>(path));
return;
}
if (i == candidates.length || left < 0) {
return;
}
dfs(i + 1, left, candidates, ans, path);
path.add(candidates[i]);
dfs(i, left - candidates[i], candidates, ans, path);
path.remove(path.size() - 1);
}
}
public class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> ans = new ArrayList<>();
Arrays.sort(candidates);
List<Integer> path = new ArrayList<>();
dfs(0, target, path, candidates, ans);
return ans;
}
private void dfs(int start, int left, List<Integer> path, int[] candidates, List<List<Integer>> ans) {
if (left == 0) {
ans.add(new ArrayList<>(path));
return;
}
if (left < 0 || start == candidates.length) {
return;
}
for (int i = start; i < candidates.length; i++) {
if (i > start && candidates[i] == candidates[i - 1]) {
continue;
}
path.add(candidates[i]);
dfs(i + 1, left - candidates[i], path, candidates, ans);
path.remove(path.size() - 1);
}
}
}
class Solution {
private final List<List<String>> ans = new ArrayList<>();
private final List<String> path = new ArrayList<>();
private String s;
public List<List<String>> partition(String s) {
this.s = s;
dfs(0);
return ans;
}
private void dfs(int start) {
if (start == s.length()) {
ans.add(new ArrayList<>(path));
return;
}
for (int end = start; end < s.length(); end++) {
if (isPalindrome(start, end)) {
path.add(s.substring(start, end + 1));
dfs(end + 1);
path.remove(path.size() - 1);
}
}
}
private boolean isPalindrome(int left, int right) {
while (left < right) {
if (s.charAt(left++) != s.charAt(right--)) {
return false;
}
}
return true;
}
}