Recursive and non-recursive implementation of full permutation algorithm

Source: Internet
Author: User

Recursive and non-recursive implementation of full permutation algorithm

The whole permutation algorithm is a common algorithm, which is used to find the whole permutation of a sequence, and the C language is implemented by recursive and non-recursive methods, which can accept input sequences with different elements.

Topics from Leetcode:

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].

Recursive implementation

For a sequence sn={s0,s1,..., Sn}, its full arrangement can be seen as s0 with the n-1 element behind it, and then the N-1 elements are then fully arranged again. This means that the full Sn arrangement can be written as {s0,sn-1},{s1,sn-1},... {sn,sn-1}. And so on This is obviously a recursive process.

#include <stdio.h>#include <stdlib.h>voidSwapint*a,int*B) {intTemp    temp = *a;    *a = *b; *b = temp;}voidPermut (int**result,intNumbers[],intNint*rows,intm) {//completion of the full array of subscript m to n    intIif(M = = N) {//processed to the last element, recursive return(*rows)--; for(i =0; I < n;    i++) result[(*rows)][i] = numbers[i]; }Else{ for(i = m; i < n; i++) {Swap (&numbers[m], &numbers[i]);//ExchangePermut (result, numbers, n, rows, M +1);//Backwards processingSwap (&numbers[m], &numbers[i]);//Exchange again}    }}int**permute (intNumbers[],intNint*numrows) {int**result, I; *numrows =1;//Calculate the total number of permutations     for(i = n; i>1; i--) (*numrows) *= i;//Allocation result arrayresult = (int**)malloc((*numrows) *sizeof(int*)); for(i =0; i< (*numrows); i++) * (result + i) = (int*)malloc(nsizeof(int));introws = *numrows;//start with the first elementPermut (result, numbers, N, &rows,0);returnResult;}intMain () {intI, J;intnumbers[3] = {1,2,2};intNumRows =0, n =3;int**result = permute (Numbers, n, &numrows); for(i =0; i<numrows; i++) { for(j =0; j<n; J + +) {printf("%d", Result[i][j]); }printf("\ n"); } System ("Pause");}
Non-recursive implementation

The idea of a non-recursive implementation of the whole arrangement is:

1, sort the sequence, generate the smallest sequence smin
2, and then find a sequence that is larger than smin but smaller than the other sequence smin+1
3, execute 2 repeatedly until the maximum sequence

For example, the sequence {2,1,3}, the first order to get the smallest sequence {* * *}, then find the minor sequence {1,3,2}, then {2,1,3} ... And so on until the sequence {3,2,1} ends.

The algorithm is in the sequence {s0,s1,... si,sj,... sk,..., Sn-1}
1, looking forward from behind, find the first Si < SJ, if I=0 is still not found, indicates that the sequence has been maximum, returned.
2, looking forward from the back, find the first element larger than Si SK, Exchange Si and SK. In order to ensure that the sub-small sequence is obtained, the sequence is si+1 to sn-1 reverse.
3, repeat 1, 22 steps until exit

#include <stdio.h>#include <stdlib.h>voidSwapint*a,int*B) {intTemp    temp = *a;    *a = *b; *b = temp;}voidSortintNumbers[],intN) {//Bubble sort    intI, J, K; for(i =0; I < n; i++) { for(j = i +1; J < N; J + +) {if(Numbers[i]>numbers[j]) swap (&numbers[i], &numbers[j]); }    }}voidReverseintNumbers[],intIintj) {//Reverse Reset    intP, q; for(p = i, q = j; p < Q; p++, q--) swap (&numbers[p], &numbers[q]);}voidStoreint**result,intNumbers[],intNintRow) {//Put the sequence in the result array    intI for(i =0; I < n; i++) Result[row][i] = numbers[i];}int**permute (intNumbers[],intNint*numrows) {int**result, I,j,row; *numrows =1; for(i = n; i>1;    i--) (*numrows) *= i; result = (int**)malloc((*numrows) *sizeof(int*)); for(i =0; i< (*numrows); i++) * (result + i) = (int*)malloc(nsizeof(int));//Sort the sequence first to find the smallest sequenceSort (numbers,n); row =0; while(true) {Store (result, numbers, n, row++);//Find the first element smaller than the latter element Numbers[i]        if(N <2)//exit directly when the sequence has only one element            returnResult for(i = n-2; I >=0; i--) {if(Numbers[i] < Numbers[i +1]) Break;Else if(i = =0)returnResult }//Find the first element larger than Numbers[i] from the back         for(j = n-1; J > i; j--) {if(Numbers[j] > Numbers[i]) Break;        } swap (&numbers[i], &numbers[j]); Reverse (numbers, i +1, N-1); }}intMain () {intI, J;intnumbers[3] = {1,2,3};intNumRows =0, n =3;int**result = permute (Numbers, n, &numrows); for(i =0; i<numrows; i++) { for(j =0; j<n; J + +) {printf("%d", Result[i][j]); }printf("\ n"); } System ("Pause");}

Recursive and non-recursive implementation of 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.