LeetCode 39 数组组合
class Solution {
List<Integer> path = new ArrayList<>();
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
test(candidates,target,0);
return res;
}
public void test(int[] candidates,int target,int index){
if(target==0){
res.add(new ArrayList<Integer>(path));
return;
}
int n = candidates.length;
for(int i=index;i<n;i++){
if(target<0){
break;
}
path.add(candidates[i]);
target-=candidates[i];
test(candidates,target,i);
path.remove(path.size()-1);
target+=candidates[i];
}
}
}
LeetCode 40 数组组合2
这里最重要的就是去重。我们发现当i>index 时,证明我们已经遍历完了所有以index为开始的所有结果,在这个时候我们取的第一位是i;如果这个时候位于i位置的数和位于i-1的数相同,那么就会出现重复的情况(所有可能出现的结果都已经在i-1的时候考虑到了)所以在这种情况下我们需要去重
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);
test(candidates,target,0);
return res;
}
public void test(int[] candidates,int target,int index){
if(target==0){
res.add(new ArrayList<Integer>(path));
return ;
}
int n =candidates.length;
for(int i=index;i<n;i++){
if(target-candidates[i]<0){
break;
}
if ( i > index && candidates[i] == candidates[i - 1] ) {
continue;
}
path.add(candidates[i]);
target-=candidates[i];
test(candidates,target,i+1);
path.remove(path.size()-1);
target+=candidates[i];
}
}
}
LeetCode 131 分割回文串
class Solution {
Deque<String> path = new LinkedList<>();
List<List<String>> res = new ArrayList<>();
public List<List<String>> partition(String s) {
test(s,0);
return res;
}
public void test(String s,int index){
if(index==s.length()){
res.add(new ArrayList<String>(path));
return ;
}
int n = s.length();
for(int i=index;i<n;i++){
if(isPa(s,index,i)){
String str = s.substring(index, i + 1);
path.addLast(str);
}else{
continue;
}
test(s,i+1);
path.removeLast();
}
}
public boolean isPa(String s,int start,int end){
while(start<=end){
if(s.charAt(start)==s.charAt(end)){
start++;
end--;
}else{
return false;
}
}
return true;
}
}

被折叠的 条评论
为什么被折叠?



