90. Subsets II

Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: [1,2,2]
Output:
[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]


class Solution:
    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
        res = []
        nums = sorted(nums)
        def backtracking(path,index):
            res.append(path.copy())
            for i in range(index,len(nums)):
                if i > index and nums[i] == nums[i-1]:
                    continue
                backtracking(path+[nums[i]],i+1)
        backtracking([],0)
        return res
            

 



 1 class Solution {
 2     
 3     List<List<Integer>> res = new ArrayList<>();
 4     
 5     public List<List<Integer>> subsetsWithDup(int[] nums) {
 6         Arrays.sort(nums);
 7         help(new ArrayList<>(), nums, 0);
 8         return res;
 9     }
10     private void help(List<Integer> temp,int[] nums,int index){
11         temp = new ArrayList<>(temp);
12         res.add(temp);
13         for(int  i= index;i<nums.length;i++){
14             if(i>index&&nums[i]==nums[i-1])
15                 continue;
16             temp.add(nums[i]);
17             help(temp,nums,i+1);
18             temp.remove(temp.size()-1);
19         }
20     }
21 }

 

posted @ 2018-04-21 17:11  乐乐章  阅读(118)  评论(0编辑  收藏  举报