码迷,mamicode.com
首页 > 其他好文 > 详细

回溯法求n的阶乘

时间:2016-10-18 22:22:38      阅读:116      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!