题目1120:全排列

题目描述:

给定一个由不同的小写字母组成的字符串,输出这个字符串的所有全排列。
我们假设对于小写字母有'a' < 'b' < ... < 'y' < 'z',而且给定的字符串中的字母已经按照从小到大的顺序排列。

输入:

输入只有一行,是一个由不同的小写字母组成的字符串,已知字符串的长度在1到6之间。

输出:

输出这个字符串的所有排列方式,每行一个排列。要求字母序比较小的排列在前面。字母序如下定义:
已知S = s1s2...sk , T = t1t2...tk,则S < T 等价于,存在p (1 <= p <= k),使得
s1 = t1, s2 = t2, ..., sp - 1 = tp - 1, sp < tp成立。

样例输入:
abc
样例输出:
abc
acb
bac
bca
cab
cba
提示:

每组样例输出结束后要再输出一个回车。

用的DFS,TLE...

Code:
#include <cstdio>
#include <cstring>
 
using namespace std;
 
const int arrSize=10;
char arr[arrSize];
bool mark[arrSize];
char answer[arrSize];
int arrLen=0;
 
void initMark(bool mark[]){
    for(int cnt=1;cnt<=arrLen;++cnt)
        mark[cnt]=true;          //初始化,设置为均未访问过
}
 
void DFS(int num){
    if(num==arrLen){
        for(int cnt=1;cnt<=arrLen;++cnt)
            printf("%c",answer[cnt]);
        printf("
");
        return;
    }
    for(int cnt=1;cnt<=arrLen;++cnt){
        if(mark[cnt]==true){
            mark[cnt]=false;
            answer[num+1]=arr[cnt];
            DFS(num+1);
            mark[cnt]=true;
        }
    }
}
 
int main()
{
    while(scanf("%s",arr+1)!=EOF){
        arrLen=strlen(arr+1);
        for(int cnt=1;cnt<=arrLen;++cnt){
            initMark(mark);
            answer[1]=arr[cnt];
            mark[cnt]=false;
            DFS(1);
        }
        printf("
");
    }
    return 0;
}
 
/**************************************************************
    Problem: 1120
    User: lcyvino
    Language: C++
    Result: Time Limit Exceed
****************************************************************/

改用STL

Code:
#include <cstdio>
#include <cstring>
#include <algorithm>
 
using namespace std;
 
int main()
{
   const int arrSize=10;
   char arr[arrSize];
   int arrLen;
   while(scanf("%s",arr)!=EOF){
        arrLen=strlen(arr);
        sort(arr,arr+arrLen);
        do{
            printf("%s
",arr);
        }while(next_permutation(arr,arr+arrLen));
        printf("
");
   }
   return 0;
}
 
/**************************************************************
    Problem: 1120
    User: lcyvino
    Language: C++
    Result: Accepted
    Time:350 ms
    Memory:1020 kb
****************************************************************/

原文地址:https://www.cnblogs.com/Murcielago/p/4168244.html