The full array of recursive algorithm

problem

Suppose  {1, 2, 3, ... n} such a sequence, find all the full array of this sequence.

Solving ideas

First there are n possibilities, determined after the first is to solve the remaining n - an arrangement the problem of data, so that you can break down the problem has been down, until at the end of the sequence, which is the termination condition.

The first bit arrangement of (non-recursive)

1 2 3
2 1 3
321 

will not consider the problem of repeated sequence element, the test sequence {1,2,3}
#include <iostream>
using namespace std;
void Perm(int list[],int from,int n)
{
    for (int i = from;i < n;i++)
    {
        the swap (List [ from ], List [I]);
         // exchange a full one output arrangement 
        for ( int I = 0 ; I <n-; I ++ )
            cout << list[i] << " ";
        COUT << endl;
         // guarantee or sequence before switching. 1 {, 2,}. 3 
        the swap (List [ from ], List [I]);
   
    }
}
int main ()
{
    int list[] = { 1,2,3 };
    Perm(list, 0, 3);
    return 0;
}

 

The arrangement of all (recursive No. 2, No. 3)

1 2 3
1 3 2
2 1 3
2 3 1
3 2 1
3 1 2
#include <iostream>
using namespace std;
void Perm(int list[],int from,int n)
{
    // loop termination condition 
    IF ( from == n-)
    {
        // exchange a full one output arrangement 
        for ( int I = 0 ; I <n-; I ++ )
            cout << list[i] << " ";
        cout << endl;
        return;
    }
    for (int i = from;i < n;i++)
    {
        the swap (List [ from ], List [I]);
         // added recursively 
        Perm (List, from + . 1 , n-);
         // guarantee or sequence before switching. 1 {, 2,}. 3 
        the swap (List [ from ], list [i]);
    }
}
int main ()
{
    int list[] = { 1,2,3 };
    Perm(list, 0, 3);
    return 0;
}

Guess you like

Origin www.cnblogs.com/zhongweizi/p/12465240.html