private List<List<Integer>> ans = newLinkedList<>(); private List<Integer> path = newLinkedList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) { backtracking(target, candidates, 0); return ans; }
privatevoidbacktracking(int target, int[] candidates, int startIndex) {
// if target is less than 0, exits if (target < 0) { return; // if find a successful combo, add it into ans }elseif (target == 0) { List<Integer> combo = newLinkedList<>(); combo.addAll(path); ans.add(combo); }
for (inti= startIndex; i < candidates.length; i++) { path.add(candidates[i]);
// note here, by seting the startIndex to i , it means that // the next element can still start with candidates[i] // this allows path like [2,2,3] // but at the mean time, it prevents the path like [3,2,2] // and through this way it removes some duplicates path backtracking(target - candidates[i], candidates, i); path.remove(path.size() - 1); } } }
private List<List<Integer>> ans = newLinkedList<>(); private List<Integer> path = newLinkedList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) { Arrays.sort(candidates);
backtracking(candidates, target, 0);
return ans; }
privatevoidbacktracking(int[] candidates, int target, int index) {
if (target < 0) { return; // if find a successful combo, add it into ans }elseif (target == 0) { List<Integer> combo = newLinkedList<>(); combo.addAll(path); ans.add(combo); }
for (inti= index; i < candidates.length; i++) { // we need to avoid the duplicates in the same level for instance, // if we are chooseing the first num and the candidates is [1, 1, 1, 2] // then the second 1 would result in duplicates // this num is same as its left one && they are in the same level // then skip it if (i > index && candidates[i] == candidates[i - 1]){ continue; }
private List<List<String>> ans = newLinkedList<>(); private List<String> path = newLinkedList<>();
public List<List<String>> partition(String s) { backtracking(s, 0); return ans;
}
// for any String such as "aabbccd" // start with "a" then "aa", then "aab" privatevoidbacktracking(String s, int startIndex) {
// if we succeed to split the whole string, return if (startIndex >= s.length()) { List<String> combo = newLinkedList<>(); combo.addAll(path); ans.add(combo); return; }
for (inti= startIndex; i < s.length(); i++) { if (isPalindrome(s, startIndex, i)) { path.add(s.substring(startIndex, i + 1)); }else { continue; }
backtracking(s, i + 1); path.remove(path.size() - 1); }
}
// test if a sub string is palindrome from startIndex to the endIndex privatebooleanisPalindrome(String s, int startIndex, int endIndex) { inti= startIndex; intj= endIndex;
booleanans=true;
while ( i <= j) { if (s.charAt(i) == s.charAt(j)){ i++; j--; }else { ans = false; break; } }