zoukankan      html  css  js  c++  java
  • 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);
                }
            }
        }
    }

     

     
  • 相关阅读:
    软件工程最后一次作业
    第四次作业(第二次结对作业)
    软件工程结对作业
    软件工程第二次作业
    软件工程第一次作业
    软件工程结对编程第二次作业
    结对编程第一次作业
    软件工程第三次作业
    软件工程第二次作业
    软件工程第一次作业
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7566562.html
Copyright © 2011-2022 走看看