Recursive Implementation (C ++) and recursion of all n Integers
Full Permutation is a very common small algorithm. The following is a Recursive Implementation of the Full Permutation of n integers, using C ++
#include <iostream>using namespace std;int n = 0;void swap(char *a ,char *b){int m ;m = *a;*a = *b;*b = m;}void perm(char list[],int k, int m ){int i;if(k >m){for(i = 0 ; i <= m ; i++){cout<<list[i];}cout<<endl;}else{for(i = k ; i <=m;i++){swap(&list[k],&list[i]);perm(list,k+1,m);swap(&list[k],&list[i]);}}}int main(){char list[] ="12345";perm(list,0,4);return 0;}
C ++ program writing, input n, output n characters in full arrangement, implemented through function Recursion
# Include <iostream> using namespace std; void output (char d [], int n) // output {for (int I = 0; I <n; I ++) cout <d [I]; cout <"" ;}void swap (char & x, char & y) // exchange {char t = x; x = y; y = t;} void perm (char d [], int n, int j) // start subscript of j {if (j = n) output (d, n ); // output else for (int I = j; I <n; I ++) {if (I! = J) swap (d [j], d [I]); // exchange perm (d, n, j + 1); // recursively arrange if (I! = J) swap (d [j], d [I]);} // restore} int main () {char a [] = {'A', 'B ', 'C', 'D', 'E', 'F', 'G', 'h', 'I', 'J', 'k', 'l ', 'M', 'n', 'O', 'P', 'Q', 'R', 's', 't', 'U', 'V ', 'w', 'x', 'y', 'z'}; int n; cout <"Enter n: \ n"; cin> n; perm (a, n, 0); cout <endl; system ("pause"); return 0;} algorithm: 1. swap the first character with n-1 character in sequence to obtain a new first letter each time. 2. the remaining n-1 letters are repeated in step 1 until all arrays are arranged;
C ++ code recursive algorithm: displays the number n of input numbers in an all-round arrangement (which is arbitrary or non-consecutive). Then, the system prompts the n numbers.
# Include <stdio. h>
# Include <string. h>
# Include <math. h>
# Include <iostream>
Using namespace std;
Const int MAX = 10;
Int a [MAX], B [MAX];
Bool used [MAX] = {false };
Void DFS (int deep, int n)
{
Int I;
If (deep = n)
{
For (I = 0; I <n; I ++) cout <B [I] <"";
Cout <endl;
Return;
}
For (I = 0; I <n; I ++)
{
If (used [I]) continue;
Used [I] = true;
B [deep] = a [I];
DFS (deep + 1, n );
Used [I] = false;
}
}
Int main ()
{
Int n, I;
Cin> n;
For (I = 0; I <n; I ++) cin> a [I];
DFS (0, n );
Return 0;
}