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

来源:互联网 发布:seo怎样 编辑:程序博客网 时间:2024/05/12 15:15

<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

0 0