diff --git a/problems/回溯算法去重问题的另一种写法.md b/problems/回溯算法去重问题的另一种写法.md index bc2763ae..f39c3c74 100644 --- a/problems/回溯算法去重问题的另一种写法.md +++ b/problems/回溯算法去重问题的另一种写法.md @@ -286,8 +286,70 @@ class Solution { } ``` +**90.子集II** +```java +class Solution { + List> reslut = new ArrayList<>(); + LinkedList path = new LinkedList<>(); + + public List> 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 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> result = new ArrayList<>(); + LinkedList path = new LinkedList<>(); + public List> 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 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**