首页 > 代码库 > 回溯法求n的阶乘

回溯法求n的阶乘

 

代码如下:

#include <iostream>#include <algorithm>#include <stdio.h>#include <cstring>#include <cmath>#include <map>#include <bitset>using namespace std;typedef long long LL;int x[105];int n;void Backtrack(int t){    if(t==n){        for(int i=1;i<=n;i++)        cout<<x[i]<<" ";        cout<<endl;        return ;    }    for(int i=t;i<=n;i++)    {        swap(x[i],x[t]);        Backtrack(t+1);        swap(x[i],x[t]);    }}int main(){    for(int i=1;i<105;i++)        x[i]=i;    while(scanf("%d",&n)!=EOF)    {        cout<<n<<"的全排列如下:"<<endl;        Backtrack(1);        cout<<"finish!"<<endl;    }    return 0;}

 

运行截图:

技术分享

 

回溯法求n的阶乘