首页 > 其他 > 详细

回溯法求n的阶乘

时间:2016-10-18 22:21:55      阅读:255      评论:0      收藏:0      [点我收藏+]

 

代码如下:

#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的阶乘

原文:http://www.cnblogs.com/chen9510/p/5974879.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!