Full permutation recursive algorithm

Source: Internet
Author: User

A recursive algorithm is given.

1, initialization of an n-dimensional array, No. 0 fill 1, 1th place fill 2 ... The n-1 bits are filled with n;

2, look at the array as two parts, one is already lined up, the rest is to row, respectively, with two pointers pointing;

3, the first character, followed by the n-1 characters, each Exchange to get a new first digit;

4. The remaining n-1 numbers are repeated at 2, 3 steps until all arrays are arranged;

Use C + + implementation, the code is still a little cumbersome, tomorrow to take a closer look at the optimization

1 #include <iostream>
2 using namespace Std;
3
4 void Swap (int *p1,int *p2)
5 {
6//Exchange P1 and P2 point to value
7 int tmp=*p1;
8 *P1=*P2;
9 *p2=tmp;
10}
one void output (int *p,int n)
12 {
while (n>0)
14 {
cout<<*p;
p++;
n--;
18}
cout<< "\ n";
20}
21st
void Fill (int *p1,int *p2,int len,int N)
{//P1 points to the filled part, always pointing to the first;
//p2 points to the remaining parts, to be inserted into that;
//len represents the length of the filled part, and n represents the length of the array
if (len==n-1)
27 {
Output (P1,n)//All arrays
29}
Or else
31 {
int *P3,*P4;
*pp= int (int *) malloc (n*sizeof (int));
for (int i=0;i<n;i++)
35 {
(pp+i) =* (p1+i);
37}
P3=PP;
while (*P3!=*P2)
40 {
p3++;
42}
P4=P3;
44
for (int i=0;i<n-len;i++)
46 {
Swap (P3,P4);
p4++;
Fill (pp,p3+1,len+1,n);
50}
51}
52}
53
inti Void (int *p,int n)
55 {//Initialize all elements in the array,
int num=1;
while (num<=n)
58 {
*p=num++;
p++;
//cout<<num<<endl;
62}
63}
64
int main ()
66 {
*p,n int;
cout<< "Please input the whole arrangement scale:";
cin>>n;
p= (int *) malloc (n*sizeof (int));
Inti (P,n);
(P,p,0,n);
0;
74}

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.