LeetCode 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],
  []
]

【题目分析】

与题目Subset类似,Subsets II中的元素是可能存在重复的。

参考Subset的解法 http://www.cnblogs.com/liujinhong/p/5555139.html


【思路】

为了避免出现重复的解,我们在进行回溯的时候要判断解空间树的当前节点的兄弟节点的值是否相同。我们首先对数组进行排序,然后使用递归回溯法来解决这个问题。


【java代码】

 1 public class Solution {
 2     public List<List<Integer>> subsetsWithDup(int[] nums) {
 3         Arrays.sort(nums);
 4         List<List<Integer>> result = new ArrayList<>();
 5         dfs(nums, 0, new ArrayList<>(), result);
 6         return result;
 7     }
 8     
 9     private void dfs(int[] nums, int idx, List<Integer> path, List<List<Integer>> ret){
10         ret.add(path);
11         for(int i = idx; i < nums.length; i++){
12             if(i > idx && nums[i] == nums[i-1])
13                 continue;
14             List<Integer> p = new ArrayList<>(path);
15             p.add(nums[i]);
16             dfs(nums, i+1, p, ret);
17         }
18     }
19 }
原文地址:https://www.cnblogs.com/liujinhong/p/5954507.html