Leetcode -- permutations II

Source: Internet
Author: User

Problem description:

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,
[1,1,2]Have the following unique permutations:
[1,1,2],[1,2,1], And[2,1,1].

Analysis: the question refers to printing all the arrays of repeated numbers. You can use a judgment function to determine whether the previous occurrence has occurred at any time. The Code is as follows:

class Solution {public:        void swap(int &a,int &b)    {        int temp=a;        a=b;        b=temp;    }        bool Isduplicate(vector<int> num,int begin,int last)    {        for(vector<int>::size_type i=begin;i!=last;++i)            if(num[i]==num[last])                return false;        return true;    }            void permutations(vector<int> num,int begin,vector<int> &permutation,vector<vector<int> > &res)    {        if(begin==num.size())        {            res.push_back(permutation);            return;        }                for(vector<int>::size_type index=begin;index!=num.size();++index)        {                        if(Isduplicate(num,begin,index))            {            swap(num[begin],num[index]);            permutation.push_back(num[begin]);            permutations(num,begin+1,permutation,res);            permutation.pop_back();            swap(num[begin],num[index]);            }                    }    }    vector<vector<int> > permuteUnique(vector<int> &num) {        vector<vector<int> > res;        if(num.empty())            return res;        vector<int> permutation;        permutations(num,0,permutation,res);        return res;    }};



Leetcode -- permutations II

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.