• lintcode18- subsetsII- medium


    Given a list of numbers that may has duplicate numbers, return all possible subsets

     Notice
    • Each element in a subset must be in non-descendingorder.
    • The ordering between two subsets is free.
    • The solution set must not contain duplicate subsets.

    Example

    If S = [1,2,2], a solution is:

    [[2], [1], [1,2,2], [2,2], [1,2], []]

    Challenge

    Can you do it in both recursively and iteratively?

    和 I 一样,仅仅加一个判断if,if (i == index || nums[i] != nums[i - 1])才进行递归。

    public class Solution {
        /*
         * @param nums: A set of numbers.
         * @return: A list of lists. All valid subsets.
         */
        public List<List<Integer>> subsetsWithDup(int[] nums) {
    
            if (nums == null){
                return null;
            }
    
            //List<List<Integer>> result = new ArrayList<>(new ArrayList<Integer>());
            List<List<Integer>> result = new ArrayList<>();
    
            if (nums.length == 0){
                result.add(new ArrayList<Integer>());
                return result;
            }
    
            Arrays.sort(nums);
            helper(new ArrayList<Integer>(), nums, 0, result);
            return result;
    
        }
    
        private void helper(List<Integer> subset, int[] nums, int index, List<List<Integer>> result){
    
            result.add(new ArrayList<Integer>(subset));
    
            for (int i = index; i < nums.length; i++){
                if (i == index || nums[i] != nums[i - 1]){
                    subset.add(nums[i]);
                    helper(subset, nums, i + 1, result);
                    subset.remove(subset.size() - 1);
                }
            }
        }
    }

     

     
  • 相关阅读:
    深度解析正则表达式exec和match两者使用的异同以及要注意的地方
    CSS中有关水平居中和垂直居中的解决办法
    Ubunut16.04 安装 Mahout
    正则表达式常用方法
    python字符串判断
    python list
    python一些包
    数据科学中的R和Python: 30个免费数据资源网站
    simple vimrc for python
    python的一些方法
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7566562.html
Copyright © 2020-2023  润新知