Lintcode subsets Ii__lintcode

Source: Internet
Author: User
Tags lintcode

question

Given a list of numbers to has duplicate numbers, return all possible subsets.

Example

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

[[2],

[1],

[1,2,2],

[2,2],

[1,2],

[] ]

Challenge

Can you did it in both recursively and iteratively? Solution

Recursion: Similar to subsets 17, but because there are duplicate elements, there are several points to be aware of in order to avoid duplicate solutions.

1 Put all the repeating elements together so that the input array is sorted first

2 The method of avoiding repetition is that the repeating element can only take the first element, so before adding an element, determine whether the element value is equal to the previous element.

Non-recursion:

The code is as follows:

Recursion:

Class Solution {public list<list<integer>> subsetswithdup (int[] nums) {LIST&LT;LIST&LT;INTEGER&G
        t;> result = new arraylist<> ();
        list<integer> list = new arraylist<> ();
        if (nums = null | | nums.length = = 0) {return result;}
        Arrays.sort (Nums);
        Helper (result, list, nums, 0);
    return result;
            
            public void Helper (list<list<integer>> result, list<integer> List, int []nums, int index) {
           if (!result.contains (list)) {Result.add (new arraylist<> (list));}
            Result.add (new arraylist<> (list));
                for (int i = index; i < nums.length; i++) {List.add (nums[i));
                Helper (result, list, nums, i+1);
            List.remove (List.size ()-1); }
   
    }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.