Full permutation algorithm

Source: Internet
Author: User
Tags knowledge base

For a given collection a{a1,a2,..., an}, where n elements are different, how to output all permutations (all permutations) of the n elements.

Recursive algorithm

Here is an example of a{a,b,c}, to illustrate the whole arrangement of the generation method, for this set, which contains 3 elements, all the arrangement of the 3!=6 species, for each arrangement, its first element has 3 choices a,b,c, for the first element is an arrangement, its second element has 2 choices b,c The first element is the arrangement of B, the second element also has 2 options a,c ..., and so on, we can correspond the entire arrangement of the set to a multi-fork tree. As shown

In this tree, each path from the root to the leaf node corresponds to a permutation of set a. Recursive algorithm can avoid the multi-fork tree construction process, directly generate a full array of sets, the code is as follows.

1 Template <typename t>2 Inlinevoid swap (t* array, unsignedint I, unsignedIntJ3{4 T =Array[i];5 Array[i] =ARRAY[J];6 Array[j] =T7}89/*10* Full array of recursive output sequences11*/12void FullArray (char* Array, size_t array_size, unsignedIntIndex13{14if (Index >=Array_size)15{16for (unsignedint i =0; i < array_size; ++I17{cout << Array[i] <<‘‘;19}20cout <<‘\ n‘;2223Return; 24 }25 26 for (unsigned int i = index; i < array_size; + + i) 27  {28  Swap (array, I, index); 29 30 FullArray1 (array, array_size, index + 1); 31 32  swap (array, I, index) ; 33 }34}     

The algorithm uses an array of primitive arrays as the 28~32 line of the parameter code, the elements of the I position, and the elements of the index position are exchanged for all elements of the Array[index + 1] to array[n], corresponding to the successor nodes of the current node, recursively calling the full array generation function. It is also necessary to restore the elements of the swap location after the call is completed for use by other descent paths.

Dictionary order

An important idea of the full permutation generation algorithm is to set the arrangement of the elements in the set a in relation to the one by one mappings in some order, and in this order, all the permutations of the set are output. This order needs to be guaranteed to be able to output all permutations, not to repeat the output of a certain arrangement, or to loop out a portion of the arrangement. The dictionary order is a way of outputting the whole arrangement with this kind of thought. Here, a{1,2,3,4} is used to illustrate the method of using the dictionary output to complete the sequence.

First, the dictionary order is a way to compare the size of a sequence that is formed by a permutation of the set a. Take a{1,2,3,4} As an example, the arrangement of the 1234<1243, the comparison method is to compare the corresponding elements of two sequences from front to back, if the current position corresponds to the same element, then continue to compare the next position, until the first element in a different position, An element with a large element value is larger than the element with a small element value in the dictionary order. Above the a1[1...4]=1234 and a2[1...4]=1243, for i=1,i=2, the corresponding elements of the two sequences are equal, but when i=2, there is a1[2]=3<a2[2]=4, so 1234<1243.

The idea of using a dictionary-ordered output is to first output the smallest permutation of the dictionary order, and then output the order of the dictionary in small permutations, ..., and finally output the largest sequence of dictionary orders. Here is a question of how to find the next permutation in the dictionary order for a known permutation. The algorithm is given here.

    • For permutation A[1...N], find the maximum value of all k that satisfies a[k]<a[k+1] (0<k<n-1), if such k does not exist, it means that the current permutation is already the largest of the dictionaries in all permutations of a, and all the arranged outputs are complete.
    • In A[K+1...N], find the element l that satisfies such conditions, so that in all A[l]>a[k] elements, a[l] gets the minimum value. That is, a[l]>a[k], but less than all other elements greater than a[k].
    • Exchange A[l] and a[k].
    • For A[K+1...N], reverses the order of the elements within that interval. That is, a[k+1] and A[n] Exchange, a[k+2] and a[n-1] exchange, ... so that the next arrangement of A[1...N] in the dictionary order is obtained.

Here we take the permutation a[1...8]=13876542 as an example to explain the above algorithm. First we find that, 1 (38) 76542, the brackets position is the first place to meet a[k]<a[k+1], at this time k=2. So we look for the smallest element larger than a[2]=3 in the interval of a[3...8], find the a[7]=4 meet the conditions, Exchange a[2] and a[7] get a new permutation 14876532, for this arrangement of 3~8 interval, reverse the element of the interval, will a[3]-a[8],a[4]-a[ 7],A[5]-A[6], respectively, the next element of 13876542 dictionary order is obtained 14235678. Here is the implementation code for the algorithm

/** Flips the elements in the array*/Inlinevoid Reverse (unsignedint*Array, size_t array_size) {for (Unsigned i =0;2 * I < array_size-1; ++i) {unsignedint t =Array[i]; Array[i] = array[array_size-1-I]; Array[array_size-1-i] =T }}inlineint Lexinext (unsignedint*Lexinum, size_t array_size) {unsignedIntI, J, K, T; i = array_size-2;while (i! = Uint_max && Lexinum[i] > lexinum[i +1]) { --I }//Maximum dictionary order reachedif (i = =Uint_max) {Return1; }for (j = array_size-1, k = Uint_max; J > i; --j) {if (LEXINUM[J) >Lexinum[i]) {if (k = =Uint_max) {k =J }Else{if (LEXINUM[J) <Lexinum[k]) {k =J }}}} t =Lexinum[i]; Lexinum[i] =LEXINUM[K]; LEXINUM[K] =T Reverse (lexinum + i +1, Array_size-i-1);Return0;}/** Arranged according to the dictionary order output*/Inlinevoid Arrayprint (Constchar* Array, size_t array_size,Const unsignedint*Lexinum) {for (unsignedint i =0; i < array_size; ++i) {cout << array[lexinum[i]] <<‘‘; } cout << "\n"  ;} /* * full-array output */void FullArray (char* array, size_ T array_size) {unsigned int lexinumber[array_size]; for (unsigned int i = 0; i < Array_ Size ++i) {Lexinumber[i] = I;} Arrayprint (Array, array_size, lexinumber); while (! Lexinext (Lexinumber, array_size)) {arrayprint (array, array_size, Lexinumber);}}      

The full arrangement of the output collection using a dictionary order needs to be noted, because the dictionary sequence involves comparisons between two permutations, and for elements that are not easy to compare, they can be indexed as elements in the array, indexed in alphabetical order, and then indexed to the corresponding set elements. This method is used by the sample code. For collection A{a,b,c,d}, you can make a full-array build of its index 1234. There is also a benefit, that is, the dictionary order of the full array generation algorithm, you need to start from the smallest order of the dictionary order to generate all the arrangement of the set, if the original collection a element is not ordered, the dictionary order method will not be able to get all the results of the arrangement, you need to sort the original set after the generation algorithm, Generates a full array of indexes, avoiding sorting operations on the original collection.

One of the advantages of dictionary-ordering algorithms is that they are not affected by duplicate elements. For example 1224, the exchange of two in the middle of 2, actually get the same arrangement, and the dictionary order is strictly in accordance with the size of the arrangement element of the relationship to generate. For input collections that contain duplicate elements, the same elements need to be put together first, as an example of a set a{a,d,b,c,d,b}, if the index 123456 is fully arranged, the desired result will not be obtained, where the repeating elements are placed adjacent to each other, and the elements are not necessarily ordered. The final result can be obtained by arranging a ' {a,d,d,b,b,c} and then using different elements, corresponding to different index values, generating an index arrangement of 122334, and then performing the full permutation algorithm.

Good text to the top concern my collection this article joke 528
Follow-0
Fans-0 + plus attention0 0? On an article: egg throwing problem
? Next: Full array generation algorithm (ii) posted @2014-03-18 11:22 joke 528 read (53) Comment (0) Edit Collection Refresh Comments Refresh page back to topRegistered users can post a comment, please login or register, visit the homepage of the website. "Recommended" 500,000 lines VC + + Source: Large configuration industrial control, power simulation CAD and GIS Source Library
"Event" Gifted Da Cong officially launches "Driverless vehicle engineer" course
"Recommended" cloud release App social white paper IM boost 8 times times more active
"Recommended" Stop writing code! Find the right tools, with less effort, all-round development tools Pack up
"Recommended" NetEase this cloud product has been published for 15 years, attracting 100,000 + developers for 1 years Latest IT News:
· The new MacBook Pro is coming, and they're going to be eliminated.
· Microsoft publishes knowledge atlas and concept tagging model to help machines better understand human
· Google CEO Pichai: Voice search technology will bring positive impact to the company
· Shared bike Mobike and Ofo trial ride experience in shared economy
· Samsung patent Application Exposure: Fingerprint gesture operation possible
? More news ... Latest Knowledge Base articles:
· Code refactoring in a gradual manner
· The authentic and wild path of technology
· Chenhao: What is an engineer culture?
· It's not that hard to talk about CSS design patterns
· Program Monkey Daughter-in-law attention matters? More Knowledge Base articles ...
< October 2016 >
Day a two three Four Five Six
25 26 27 28 29 30 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21st 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
Nickname: Joke 528
Garden Age: 2 years 11 months
Fans: 0
Follow: 0+ plus follow search

Common links
    • My essay.
    • My comments
    • My participation
    • Latest comments
    • My tags
    • More links
My tags
    • grep (1)
    • Linux (1)
Essays Archive
    • June 2014 (2)
    • March 2014 (11)
    • November 2013 (2)
Read the leaderboard
    • 1. bit operation priority!!! (97)
    • 2. Maximum substring and problem (89)
    • 3. Full array generation algorithm (iii) (74)
    • 4. BM algorithm detailed (55)
    • 5. Full array generation algorithm (i) (54)
The Copyright? 2016 jokes 528

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.