90. 子集 II

  1. 90. 子集 II
  • 题解
  • 90. 子集 II

    难度中等326

    给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

    说明:解集不能包含重复的子集。

    示例:

    输入: [1,2,2]
    输出:
    [
      [2],
      [1],
      [1,2,2],
      [2,2],
      [1,2],
      []
    ]

    通过次数53,253

    提交次数86,972

    在真实的面试中遇到过这道题?

    题解

    class Solution {
        public List<List<Integer>> subsetsWithDup(int[] nums) {
            //排序后保证相邻的是重复元素
            Arrays.sort(nums);
            List<List<Integer>> res = new ArrayList<>();
            trackBack(nums, 0, new LinkedList<Integer>(), res);
            return res;
        }
    
        void trackBack(int[] nums, int start, LinkedList<Integer> temp , List<List<Integer>> res){
            res.add(new LinkedList<>(temp));
            for(int i=start; i < nums.length; i++){
                if( i > start && nums[i] == nums[i-1]){ // i> start 是为了保证从start+1开始
                    continue;
                }
                temp.add(nums[i]);
                trackBack(nums,i+1,temp,res);
                temp.pollLast();
            }
        }
    }

    转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 mym_74@163.com