组合总和
List<List<Integer>> res=new ArrayList<List<Integer>>();
LinkedList<Integer> path=new LinkedList<Integer>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
buildCombination(candidates,target,0,0);
return res;
}
public void buildCombination(int[] candidates, int target,int sum,int index){
if(sum>target)return;
if(sum==target){
res.add(new ArrayList<>(path));
return;
}
for(int i=index;i<candidates.length;i++){
path.add(candidates[i]);
sum+=candidates[i];
buildCombination(candidates,target,sum,i);
path.removeLast();
sum-=candidates[i];
}
}
组合总和 II
List<List<Integer>> res=new ArrayList<List<Integer>>();
LinkedList<Integer> path=new LinkedList<Integer>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
buildCombination(candidates,target,0,0);
return res;
}
public void buildCombination(int[] candidates, int target,int sum,int index){
if(sum==target){
res.add(new ArrayList<>(path));
return;
}
for(int i=index;i<candidates.length&&sum+candidates[i]<=target;i++){
if(i>index&&candidates[i]==candidates[i-1]){
continue;
}
sum+=candidates[i];
path.add(candidates[i]);
buildCombination(candidates,target,sum,i+1);
sum-=candidates[i];
path.removeLast();
}
}
分割回文串
List<List<String>> res=new ArrayList<List<String>>();
LinkedList<String> path=new LinkedList<String>();
boolean[][]dp;
public List<List<String>> partition(String s) {
int len=s.length();
dp=new boolean[len][len];
computePalindrome(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(dp[index][i]){
path.add(s.substring(index,i+1));
backtracking(s,i+1);
path.removeLast();
}
}
}
public void computePalindrome(String s){
char[]c= s.toCharArray();
for(int i=s.length();i>=0;i--){
for(int j=i;j<s.length();j++){
if(c[i]==c[j]){
if(j-i<=1||dp[i+1][j-1])dp[i][j]=true;
}
}
}
}