zoukankan      html  css  js  c++  java
  • leetcode 90. 子集 II JAVA

    题目:

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

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

    示例:

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

    思路:

    public class Solution {
        List<List<Integer>> res;//结果集
        List<Integer> al;//每一项
        public List<List<Integer>> subsetsWithDup(int[] nums) {
            res = new ArrayList<List<Integer>>();
            al = new ArrayList<Integer>();
            Arrays.sort(nums); //将数组进行排序
            count(nums,al,0);
            return res;
        }
        
        private void count(int[] nums,List<Integer> al,int j){
          
            res.add(new ArrayList<Integer>(al));//不重复的才添加
            for(int i = j; i < nums.length;i++){
                if(i == j || nums[i] != nums[i-1]){//去除重复
                    al.add(nums[i]);//添加
                    count(nums,al,i+1);
                    al.remove(al.size()-1);//去除,为下一个结果做准备
                }
            }
        }
        
    }
  • 相关阅读:
    资源与锁
    资源与锁
    Leetcode-Rotate List
    Leetcode-Unique Paths II
    Leetcode-Unique Paths
    Leetcode-Minimum Path Sum
    Leetcode-Sqrt(x)
    Leetcode-Set Matrix Zeroes
    Leetcode-Search a 2D Matrix
    Leetcode-Combinations
  • 原文地址:https://www.cnblogs.com/yanhowever/p/10736638.html
Copyright © 2011-2022 走看看