Leetcode (permutations)

Source: Internet
Author: User

Topic

Given A collection of numbers, return all possible permutations.

For example,
[following] has the permutations:
[1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].

Analysis

The problem of the full permutation of all elements in the array of directional quantities.

We know n Element has n! , while STL's underlying files < algorithm > have standard algorithms for arranging elements:

    1. bool next_permutation(BidirectionalIterator beg , BidirectionalIterator end);
      This function changes the order of elements within the interval [beg, end] so that they conform to the "next order"
    2. bool prev_permutation(BidirectionalIterator beg , BidirectionalIterator end);
      This function changes the order of elements within the interval [beg, end] so that they conform to the "previous order"

If the elements are arranged in a "normal" order (in terms of the dictionary order), the two algorithms return true. The so-called formal order, for next_permutation () is ascending, to Prev_permutation () is descending. So to go through all permutations, you must sort all the elements in ascending or descending order, and then call the Next_permutation () or prev_mutation () function in a circular fashion until the algorithm returns false.

The complexity of the above two algorithms is linear, with a maximum of N/2 switching operations performed.

AC Code
classSolution { Public: vector<vector<int>>Permute ( vector<int>& Nums) { vector<vector<int> >Retif(Nums.empty ())returnRet        Sort (Nums.begin (), Nums.end ()); Ret.push_back (Nums); while(Next_permutation (Nums.begin (), Nums.end ())) Ret.push_back (nums);returnRet }};

GitHub test Program source code

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Leetcode (permutations)

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.