Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d2bbea4

Browse files
Merge pull request youngyangyang04#1954 from sharky7pb/master
添加了回溯另一种写法90.子集II的java版本
2 parents fe17873 + 29e1a07 commit d2bbea4

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

‎problems/回溯算法去重问题的另一种写法.md‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -286,8 +286,70 @@ class Solution {
286286
}
287287
288288
```
289+
**90.子集II**
290+
```java
291+
class Solution {
292+
List<List<Integer>> reslut = new ArrayList<>();
293+
LinkedList<Integer> path = new LinkedList<>();
294+
295+
public List<List<Integer>> subsetsWithDup(int[] nums) {
296+
if(nums.length == 0){
297+
reslut.add(path);
298+
return reslut;
299+
}
300+
Arrays.sort(nums);
301+
backtracking(nums,0);
302+
return reslut;
303+
}
289304

305+
public void backtracking(int[] nums,int startIndex){
306+
reslut.add(new ArrayList<>(path));
307+
if(startIndex >= nums.length)return;
308+
HashSet<Integer> hashSet = new HashSet<>();
309+
for(int i = startIndex; i < nums.length; i++){
310+
if(hashSet.contains(nums[i])){
311+
continue;
312+
}
313+
hashSet.add(nums[i]);
314+
path.add(nums[i]);
315+
backtracking(nums,i+1);
316+
path.removeLast();
317+
}
318+
}
319+
}
320+
```
321+
**40.组合总和II**
322+
```java
323+
class Solution {
324+
List<List<Integer>> result = new ArrayList<>();
325+
LinkedList<Integer> path = new LinkedList<>();
326+
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
327+
Arrays.sort( candidates );
328+
if( candidates[0] > target ) return result;
329+
backtracking(candidates,target,0,0);
330+
return result;
331+
}
290332

333+
public void backtracking(int[] candidates,int target,int sum,int startIndex){
334+
if( sum > target )return;
335+
if( sum == target ){
336+
result.add( new ArrayList<>(path) );
337+
}
338+
HashSet<Integer> hashSet = new HashSet<>();
339+
for( int i = startIndex; i < candidates.length; i++){
340+
if( hashSet.contains(candidates[i]) ){
341+
continue;
342+
}
343+
hashSet.add(candidates[i]);
344+
path.add(candidates[i]);
345+
sum += candidates[i];
346+
backtracking(candidates,target,sum,i+1);
347+
path.removeLast();
348+
sum -= candidates[i];
349+
}
350+
}
351+
}
352+
```
291353
Python:
292354

293355
**90.子集II**

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /