mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Merge pull request #1954 from sharky7pb/master
添加了回溯另一种写法90.子集II的java版本
This commit is contained in:
@ -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**
|
||||
|
Reference in New Issue
Block a user