求一个数的全排列的一种思路

<span style="font-family:Courier New;">
</span>
<span style="font-family:Courier New;">今天突然想试一下1,2,3,4,5,的全排列数,思考了一下,解决方案很普通,复杂度极高,是O(n!),首先从第一个数开始,有五种选择,第二个数四种。。。。暴力加回溯就ok。
</span>
<span style="font-family:Courier New;">
</span>
<span style="font-family:Courier New;">
</span>
<span style="font-family:Courier New;">#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;

const int MAXN=100+5;
char a[MAXN];
bool book[MAXN];
int Count=0;

void f(char a[],int k,int n);

int main() {
    freopen("D:\\output.txt","w",stdout);
    int n;
    cin>>n;
    memset(a,0,sizeof(a));
    memset(book,0,sizeof(book));
    f(a,1,n);
    return 0;
}

void f(char a[],int k,int n) {
    if(k>n) {
        cout<<++Count<<": ";
        puts(a);
        return;
    }
    for(int i=1;i<=n;i++) {
        if(!book[i]) {
            a[k-1]=i+'0';
            book[i]=1;
            f(a,k+1,n);
            a[k-1]='\0';
            book[i]=0;
        }
    }
}</span>

4    //运行结果
1: 1234
2: 1243
3: 1324
4: 1342
5: 1423
6: 1432
7: 2134
8: 2143
9: 2314
10: 2341
11: 2413
12: 2431
13: 3124
14: 3142
15: 3214
16: 3241
17: 3412
18: 3421
19: 4123
20: 4132
21: 4213
22: 4231
23: 4312
24: 4321

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值