mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
回溯算法去重问题的另一种写法,40.组合总和II的java版本
This commit is contained in:
@ -317,7 +317,38 @@ class Solution {
|
||||
}
|
||||
}
|
||||
```
|
||||
**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