zoukankan      html  css  js  c++  java
  • subsets II

    Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

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

    这题也是求子集,但是元素可能会有重复的。所以要排序,然后跳过重复元素。因为每次遍历不是从头开始,所以跳过重复元素时,不需要利用额外的数组。

    代码如下:

    class Solution {
        public List<List<Integer>> subsetsWithDup(int[] nums) {
            List<List<Integer>> res=new ArrayList<List<Integer>>();
            if(nums==null||nums.length==0) return res;
            Arrays.sort(nums);  //有相同元素,所以要排序
            helper(res,new ArrayList<Integer>(),nums,0);
            return res;
        }
        public void helper(List<List<Integer>> res,List<Integer> list,int[] nums,int index){
            //求子集,所以判断条件为.而且满足条件后还要继续向下进行,而不是返回
            if(list.size()<=nums.length)
                res.add(new ArrayList<Integer>(list));
            for(int i=index;i<nums.length;i++){
                //跳过相同的元素。因为是从后面的元素中选元素,不是从头开始,所以不需要再创建是否使用的数组了。注意:下面是i>index,而不是i>0.
                if(i>index&&nums[i]==nums[i-1]) continue;  
                list.add(nums[i]);
                helper(res,list,nums,i+1);
                list.remove(list.size()-1);
            }
        }
    }
  • 相关阅读:
    安装redis
    memcached复制-repcached
    memcached一致性哈希及php客户端实现
    安装php
    安装mysql
    安装apache
    putty配色方案
    virtualbox下centos实现主宿互访
    安装memcached
    linux网络、性能相关命令
  • 原文地址:https://www.cnblogs.com/xiaolovewei/p/8183194.html
Copyright © 2011-2022 走看看