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

来源:互联网 发布:首趣优店可开淘宝店吗 编辑:程序博客网 时间:2024/04/27 19:25

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;    }}
0 0
原创粉丝点击