Subsets II 解答

Question

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

Note:

  • Elements in a subset must be in non-descending order.
  • 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],
  []
]

Solution

Similar with Subset I. Here, we need to consider how to deal with duplicates.

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

Conclusion -- Two ways to deal with duplicates in result

如这一题,输入数组中有重复数字,所以如果不考虑处理重复,结果中也会有重复数字。

有两种处理重复的方法。

1. 加入result前,判断该子结果是否已经存在。

2. Skip 方法

方法一会造成大量时间空间浪费,所以不建议。下面重点总结方法二。

以该题为例,我们画出它的解空间树。

我们发现其实重复的部分就是相当于重复的子树,因此直接跳过重复的数字即可。

 

posted @ 2015-10-19 05:10  树獭君  阅读(343)  评论(0编辑  收藏  举报