Leetcode 90. Subsets II 子集2 解题报告

1 解题思想

这道题有一个简化版,没有看的可以先看看

Leetcode 78. Subsets 子集 解题报告

这道题更复杂的原因在于,给定的数组会存在重复的情况,实际的解法也很common,我相信我已经在之前很多的解题里面说过了,背下来就好:

0、首先需要排序,然后用回溯的方式组合选择,序列在递归到最后一个位置时生成。
规则0:所有数都有不选的这种状况
规则1:第一个数(index=0)可以选
规则2:在任何情况下,当一个数(位置index)和前一个数(index-1)的数值不相同时,可以选中,也可以不选中
规则3:任何情况下,当一个数(位置index)和前一个数(index-1)的数值相同时,当且仅当index-1的数字被选中了,index才能被选中,否则index不能选中

2 原题

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




Subscribe to see which companies asked this question

3 AC 解

public class Solution {
    boolean flag[] ;
    List<List<Integer>> result;
    public void search(int[] nums,int index){
        if(index == nums.length){
            List<Integer> list = new ArrayList<Integer>();
            for(int i=0;i<index;i++){
                if(flag[i]==true){
                    list.add(nums[i]);
                }
            }
            result.add(list);
            return;
        }
        search(nums,index+1);
        if(index==0 || nums[index-1]!=nums[index] || flag[index-1]==true){
            flag[index]=true;
            search(nums,index+1);
            flag[index]=false;
        }

    }
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        this.flag = new boolean[nums.length];
        result = new ArrayList<List<Integer>>();
        search(nums,0);
        return result;


    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值