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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值