全排列的递归算法

递归思想来进行全排列是最接近人的思维的,例如对a, b , c,进行全排列第一轮是a**,b**,c**,第二轮是ab*,b a*, c b*,就是轮番把一个数固定在首位,然后剩下几位进行枚举;
代码:
#include
using namespace std;
int total = 0;
//交换函数
void swapArray(int &a,int &b)
{
    int temp;
    temp = a;
    a = b;
    b = temp;
}
//递归函数
void fullPermutation(int * fullArray,int start,int endn,int number){
    //这里,既可以是">=",也可以是">",,应该也可以是"=="
    if(start>=endn){
        for(int i=0;i
            cout<<fullArray[i];
        }
        cout<<endl;
        total++;
    }
    else{
        for(int i=start;i<=endn;i++){
            swapArray(fullArray[start],fullArray[i]);//交换
            fullPermutation(fullArray,start+1,endn,number);
            swapArray(fullArray[start],fullArray[i]);//注意恢复原样
        }
    }
}
int main()
{
    int number;//全排列的长度
    cout<<"Number:"<<endl;
    cin>>number;
    int * fullArray = new int[number];//动态生成全排列的数组
    //初始化
    for (int i=0;i
    {
        fullArray[i] = i+1;
    }
    fullPermutation(fullArray,0,number-1,number);
    cout<<"Total = "<<total;
    return 0;
}

原文地址:https://www.cnblogs.com/wuwangchuxin0924/p/5781633.html