[Leetcode] Permutations II Arrangement

Source: Internet
Author: User

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

For example,
[1,1,2]The following unique permutations:
[1,1,2], [1,2,1] , and [2,1,1] .

Show TagsBacktracking This is the input an array, there may be duplicates, the output of all the arrangement. The question called STL is as follows:
1#include <vector>2#include <iterator>3#include <algorithm>4#include <iostream>5 using namespacestd;6 7 classSolution {8  Public:9vector<vector<int> > Permuteunique (vector<int> &num) {Ten         intn =num.size (); Onevector<vector<int> >ret; A         if(n<1)returnret; -         if(n<2) {ret.push_back (num);returnret;} - sort (Num.begin (), Num.end ()); the ret.push_back (num); -          while(Next_permutation (Num.begin (), Num.end ())) { - ret.push_back (num); -         } +         returnret; -     } + }; A  at intMain () - { -vector<int> num = {1,1,2}; - solution Sol; -vector<vector<int> > RET =sol.permuteunique (num); -      for(intI=0; I<ret.size (); i++){ inCopy (Ret[i].begin (), Ret[i].end (),ostream_iterator<int> (cout," ")); -cout<<Endl; to     } +     return 0; -}
View Code

If you do not call, is to write a next_permutation, in permutations wrote a good many versions, review the implementation of the STL logic it:

    1. Input array a[], from right-to-left traversal, looking for adjacent two numbers, so that left<mid, not found? Just no, return false.
    2. Again from the right to the left to traverse, to look for >left, this time you do not need to be connected to the back, because there are 1 of this, so there is a guaranteed value (mid)
    3. Swap left and right.
    4. Reverse mid and its right.
    5. End.

[Leetcode] Permutations II Arrangement

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.