给出一个字符串S(可能有重复的字符),按照字典序从小到大,输出S包括的字符组成的所有排列。例如:S = "1312",
输出为:
1123
1132
1213
1231
1312
1321
2113
2131
2311
3112
3121
3211
Input输入一个字符串S(S的长度 <= 9,且只包括0 - 9的阿拉伯数字)Output输出S所包含的字符组成的所有排列
Sample Input
1123
Sample Output
1123 1132 1213 1231 1312 1321 2113 2131 2311 3112 3121 3211
这个代码有些卡时间,总的思路为
1.把所给的n位数整数全排列
2·排列后放入String 类型的str【】容器中
3·用sort、函数将str排列
3.因为会有重复,所以用unique将str去重。 unique详解:点击打开链接
4.输出
代码如下:
#include <iostream>
#include <stdio.h>#include <algorithm>
#include <cstring>
#include<cmath>
#define N 400009 //此处一定要用此方法给str定容,不然会超时
using namespace std;
char dex[11]; //用来存放题中所给的数
int len;int p=0;
string str[N]; //用来存放dex的全排列
void pailie(int i) //递归全排列{
if(i==len-1){
str[p++]=dex; 将dex的全排列赋给str
return;
}
for(int j=i;j<len;j++)
{
swap(dex[i],dex[j]);
pailie(i+1);
swap(dex[i],dex[j]);
}
}
int main()
{
gets(dex);
len=strlen(dex);
pailie(0);
sort(str,str+p); //排列
p=unique(str,str+p)-str; //p为去重过后str的长度
for(int i=0;i<p;i++) //输出
{
cout<<str[i]<<"\n";
}
return 0;
}