Skip to content

Commit

Permalink
Merge pull request youngyangyang04#1954 from sharky7pb/master
Browse files Browse the repository at this point in the history
添加了回溯另一种写法90.子集II的java版本
  • Loading branch information
youngyangyang04 authored Mar 29, 2023
2 parents fe17873 + 29e1a07 commit d2bbea4
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions problems/回溯算法去重问题的另一种写法.md
Original file line number Diff line number Diff line change
Expand Up @@ -286,8 +286,70 @@ class Solution {
}
```
**90.子集II**
```java
class Solution {
List<List<Integer>> reslut = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();

public List<List<Integer>> subsetsWithDup(int[] nums) {
if(nums.length == 0){
reslut.add(path);
return reslut;
}
Arrays.sort(nums);
backtracking(nums,0);
return reslut;
}

public void backtracking(int[] nums,int startIndex){
reslut.add(new ArrayList<>(path));
if(startIndex >= nums.length)return;
HashSet<Integer> hashSet = new HashSet<>();
for(int i = startIndex; i < nums.length; i++){
if(hashSet.contains(nums[i])){
continue;
}
hashSet.add(nums[i]);
path.add(nums[i]);
backtracking(nums,i+1);
path.removeLast();
}
}
}
```
**40.组合总和II**
```java
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort( candidates );
if( candidates[0] > target ) return result;
backtracking(candidates,target,0,0);
return result;
}

public void backtracking(int[] candidates,int target,int sum,int startIndex){
if( sum > target )return;
if( sum == target ){
result.add( new ArrayList<>(path) );
}
HashSet<Integer> hashSet = new HashSet<>();
for( int i = startIndex; i < candidates.length; i++){
if( hashSet.contains(candidates[i]) ){
continue;
}
hashSet.add(candidates[i]);
path.add(candidates[i]);
sum += candidates[i];
backtracking(candidates,target,sum,i+1);
path.removeLast();
sum -= candidates[i];
}
}
}
```
Python:

**90.子集II**
Expand Down

0 comments on commit d2bbea4

Please sign in to comment.