Problem A: 进阶递归之全排列
Time Limit: 1 Sec Memory Limit: 64 MB
Submit: 58 Solved: 19
[
Submit][
Status][
Web Board]
Description
给定一个由不同的小写字母组成的字符串,输出这个字符串的所有全排列。 我们假设对于小写字母有'a' < 'b' < ... < 'y' < 'z',而且给定的字符串中的字母已经按照从小到大的顺序排列。
Input
输入只有一行,是一个由不同的小写字母组成的字符串,已知字符串的长度在1到6之间。
Output
输出这个字符串的所有排列方式,每行一个排列。要求字母序比较小的排列在前面。字母序如下定义: 已知S = s1s2...sk , T = t1t2...tk,则S < T 等价于,存在p (1 <= p <= k),使得 s1 = t1, s2 = t2, ..., sp - 1 = tp - 1, sp < tp成立。
Sample Input
abc
Sample Output
abc
acbbacbcacabcba
#include <iostream>
#include <algorithm>
#include<string.h>
using namespace std;
void permutation(char* str,int length)
{
sort(str,str+length);
do
{
for(int i=0;i<length;i++)
cout<<str[i];
cout<<endl;
}while(next_permutation(str,str+length));
}
int main(void)
{
char str[10];
cin>>str;
permutation(str,strlen(str));
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
void swapa(char *a,char *b)
{
char t;
t=*a;
*a=*b;
*b=t;
}
void print(char s[],int begin,int end)
{
int i,j,n=0;
char t,str[10][10];
if(begin==end)
{
strcpy(str,s);
n++;
printf("\n");
}
else
{
for(i=begin; i<=end; i++)
{
swapa(&s[i],&s[begin]);
print(s,begin+1,end);
swapa(&s[i],&s[begin]);
}
}
}
int main()
{
char s[100];
gets(s);
print(s,0,strlen(s)-1);
return 0;
}