90. Subsets II

题目:

Given a collection of integers that might contain duplicates, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,2], a solution is:

[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

链接:https://leetcode.com/problems/subsets-ii/#/description

4/22/2017

算法班

37%, 3ms

与第78题只有一句话的区别,就是第21行去重

 1 public class Solution {
 2 
 3     public List<List<Integer>> subsetsWithDup(int[] nums) {
 4         // write your code here
 5         List<List<Integer>> ret = new ArrayList<>();
 6         
 7         Arrays.sort(nums);
 8         
 9         helper(ret, new ArrayList<Integer>(), nums, 0);
10         
11         return ret;
12     }
13     
14     private void helper(List<List<Integer>> ret,
15                         ArrayList<Integer> subset,
16                         int[] nums,
17                         int startIndex) {
18         ret.add(new ArrayList<Integer>(subset));
19         
20         for (int i = startIndex; i < nums.length; i++) {
21             if (i > startIndex && nums[i] == nums[i - 1]) continue;
22             subset.add(nums[i]);
23             helper(ret, subset, nums, i + 1);
24             subset.remove(subset.size() - 1);
25         }
26     }    
27 }

别人iterative的解释

https://discuss.leetcode.com/topic/4661/c-solution-and-explanation

更多讨论:

https://discuss.leetcode.com/category/98/subsets-ii

posted @ 2017-04-23 07:25  panini  阅读(168)  评论(0编辑  收藏  举报