39.组合总和
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> res = new LinkedList<>();
List<Integer> linkedList = new LinkedList<>();
process(res, linkedList, candidates, 0, 0, target);
return res;
}
public void process(List<List<Integer>> res, List<Integer> linkedList, int[] candidates,
int cur, int sum, int target) {
if (sum == target) {
List<Integer> temp = new LinkedList<>(linkedList);
res.add(temp);
return;
}
for (int i = cur; i < candidates.length && sum + candidates[i] <= target; i++) {
sum += candidates[i];
linkedList.add(candidates[i]);
process(res, linkedList, candidates, i, sum, target);
sum -= candidates[i];
linkedList.remove(linkedList.size() - 1);
}
}
}
40.组合总和II
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> res = new LinkedList<>();
List<Integer> linkedList = new LinkedList<>();
boolean[] usd = new boolean[candidates.length];
Arrays.sort(candidates);
process(res, linkedList, usd, 0, 0, candidates, target);
return res;
}
public void process(List<List<Integer>> res, List<Integer> linkedList, boolean[] used, int cur, int sum, int[] candidates, int target) {
if (sum == target) {
List<Integer> temp = new LinkedList<>(linkedList);
res.add(temp);
return;
}
for (int i = cur; i < candidates.length && sum + candidates[i] <= target; i++) {
if (i > 0 && !used[i - 1] && candidates[i] == candidates[i - 1]) {
continue;
}
linkedList.add(candidates[i]);
sum += candidates[i];
used[i] = true;
process(res, linkedList, used, i + 1, sum, candidates, target);
sum -= candidates[i];
linkedList.remove(linkedList.size() - 1);
used[i] = false;
}
}
}
131.分割回文串
class Solution {
List<List<String>> lists = new ArrayList<>();
Deque<String> deque = new LinkedList<>();
public List<List<String>> partition(String s) {
backTracking(s, 0);
return lists;
}
private void backTracking(String s, int startIndex) {
if (startIndex >= s.length()) {
lists.add(new ArrayList(deque));
return;
}
for (int i = startIndex; i < s.length(); i++) {
if (isPalindrome(s, startIndex, i)) {
String str = s.substring(startIndex, i + 1);
deque.addLast(str);
} else {
continue;
}
backTracking(s, i + 1);
deque.removeLast();
}
}
private boolean isPalindrome(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;
}
}