003:全排列

描述

给定一个由不同的小写字母组成的字符串,输出这个字符串的所有全排列。 我们假设对于小写字母有'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
参考代码
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
using namespace std;
const int M = 8;
char str[M];
char permutation[M];
bool used[M] = {0};
int L = 0;
void Permutation(int n)
{    
    if( n == L ) {
        permutation[L] = 0;
        cout << permutation << endl;
        return ;
    }
    for(int i = 0;i < L; ++i) {
        if( !used[i]) {
            used[i] = true;
            permutation[n] = str[i];
            Permutation(n+1);
            used[i] = false;
        }
    }
}
int main()
{
    cin >> str;
    L = strlen(str);
    sort(str,str+L);
    Permutation(0);
    return 0;    
}

我的代码
#include<cstdio>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<map>
#include<algorithm>
#include<cstring>
#define DEBUG(x) cout << #x << " = " << x << endl
using namespace std;
int num=0;
char s[10],result[10];
int N;
void permute(char c[],int n)
{
    char s[10];
    if(n==1){
        result[num++]=c[0];
        result[num]='';
        printf("%s
",result);
        num--;
        return;
    }
    for(int i=0;i<n;i++){
        //printf("%c",c[i]);
        result[num++]=c[i];
        int p=0;
        for(int k=0;k<n;k++){
            if(k!=i){
                s[p++]=c[k];
            }
        }
        permute(s,p);
        num--;
    }
}
int main()
{
    freopen("in.txt","r",stdin);
    scanf("%s",s);
    permute(s,strlen(s));
    return 0;
}

原文地址:https://www.cnblogs.com/MalcolmMeng/p/9097048.html