1. 程式人生 > >003:全排列

003:全排列

mes string tor != math 而且 n) 不同的 oid

描述

給定一個由不同的小寫字母組成的字符串,輸出這個字符串的所有全排列。 我們假設對於小寫字母有‘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]=\0;
        printf("%s\n",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;
}

003:全排列