39. 组合总和
给你一个 无重复元素 的整数数组 candidates
和一个目标整数 target
,找出 candidates
中可以使数字和为目标数 target
的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates
中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target
的不同组合数少于 150
个。
示例 1:
输入:candidates =[2,3,6,7],
target =7
输出:[[2,2,3],[7]] 解释: 2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。 7 也是一个候选, 7 = 7 。 仅有这两种组合。
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, 0);
return res;
}
public void backtracking(int[] candidates, int target, int index, int sum){
if(index == candidates.length || sum >= target ){
if(sum == target) res.add(new ArrayList(path));
return;
}
for(int i = index; i < candidates.length; i++){
sum += candidates[i];
path.add(candidates[i]);
backtracking(candidates, target, i, sum);
sum -= candidates[i];
path.remove(path.size() - 1);
}
}
}
40.组合总和II
给定一个候选人编号的集合 candidates
和一个目标数 target
,找出 candidates
中所有可以使数字和为 target
的组合。
candidates
中的每个数字在每个组合中只能使用 一次 。
注意:解集不能包含重复的组合。
示例 1:
输入: candidates =[10,1,2,7,6,1,5]
, target =8
, 输出: [ [1,1,6], [1,2,5], [1,7], [2,6] ]
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, 0);
return res;
}
public void backtracking(int[] candidates, int target, int index, int sum, int pre){
if(index == candidates.length || sum >= target ){
if(sum == target) res.add(new ArrayList(path));
return;
}
for(int i = index; i < candidates.length; i++){
if ( i > index && candidates[i] == candidates[i - 1] ) {
continue;
}
sum += candidates[i];
path.add(candidates[i]);
backtracking(candidates, target, i+1, sum, pre);
sum -= candidates[i];
path.remove(path.size() - 1);
pre = candidates[i];
}
}
}
131.分割回文串
给你一个字符串 s
,请你将 s
分割成一些子串,使每个子串都是 回文串。返回 s
所有可能的分割方案。
示例 1:
输入:s = "aab" 输出:[["a","a","b"],["aa","b"]]
class Solution {
List<List<String>> res = new ArrayList<>();
List<String> path = new ArrayList<>();
public List<List<String>> partition(String s) {
backtracking(s, 0);
return res;
}
public void backtracking(String s, int index){
if(index == s.length()){
res.add(new ArrayList<>(path));
return;
}
for(int i = index; i < s.length(); i++){
if(isPalindromic(s, index, i) == true){
String str = s.substring(index, i+1);
path.add(str);
}else{
continue;
}
backtracking(s, i+1);
path.removeLast();
}
}
public boolean isPalindromic(String s, int start, int end){
while(start < end){
if(s.charAt(start) != s.charAt(end)){
return false;
}
start++;
end--;
}
return true;
}
}