Next_permutation (full permutation algorithm)

Source: Internet
Author: User

The STL provides two algorithms for calculating the permutations and combinations of relationships, namely Next_permutation and prev_permutation.

First explain the whole arrangement, as the name implies, that is, a group of numbers of the whole arrangement of the case.

Next_permutation is a list of all the permutations of a group of numbers, but the order of the list has a certain rules, the following is about Next_permutation listed the rules of precedence ...

Rules

1. First from the end of the beginning to look forward to two adjacent elements, so that the first element is *i, the second element is *ii, and satisfies *i<*ii.

2. After finding such a group of adjacent elements, then from the end of the forward test, to find the first element greater than *i, so that the *j, the i,j element Swap (swap).

3. Sort all the elements after the II (reverse) backwards.

For example, assuming that there is a sequence {0,1,2,3,4}, the above algorithm is applied to get the "next" permutation in one step. In the picture, only the two adjacent elements that conform to "one element is *i, the second element is *ii, and satisfy *i<*ii" are not shown in the search for proper J, swap, and reversal operations.

0 1 2 3 4-"0 1 2 4 3-" 0 1 3 2 4-"0 1 3 4 2-" 0 1 4 2 3-"0 1 4 3 2 ...

Just contact is not to say very clearly, to a simple application

Full arrangement of outputs (0 1 2 3 4)

#include <iostream>
#include <algorithm>
using namespace Std;
int main ()
{
int ans[5]={0,1,2,3,4};
Sort (ans,ans+5); /* This sort can be used, because {0, 1,2,3,4} is already ordered */
DO/* Note this step, if it is a while loop, you need to output */
{
for (int i=0;i<5;++i)
cout<<ans[i]<< "";
cout<<endl;
}while (Next_permutation (ans,ans+5));
return 0;
}


Say so much first, wait for later to make up Ba ba ....

Next_permutation (full permutation algorithm)

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.