链接
给出一个字符串S(可能有重复的字符),按照字典序从小到大,输出S包括的字符组成的所有排列。例如:S = “131”,
输出为:
113
131
311
Input
输入一个字符串S(S的长度 <= 9,且只包括0 - 9的阿拉伯数字)
Output
输出S所包含的字符组成的所有排列
Sample
Inputcopy
1312
Outputcopy
1312
1123
1132
1213
1231
1312
1321
2113
2131
2311
3112
3121
3211
分析:全排列函数或者搜索
函数:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
char n[10];
int main()
{
int l;
cin>>n;
l=strlen(n);
sort(n,n+l);//字符串也可以sort排序!!!
do
{
cout<<n<<endl;
}while(next_permutation(n,n+l));
}
扩展:
a.函数模板:
lower_bound(arr[],arr[]+size,indx)
b.参数说明:
arr[] : 数组首地址
size : 数组元素的个数
indx : 需要查找的值
c.函数功能:函数lower_bound()在first和last的前闭后开区间进行二分查找,返回大于或等于val的第一个元素的位置,如果所有元素都小于val,则返回last的位置。
a. 函数模板 : upper_bound(arr[] , arr[]+size , indx)
b. 参数说明:
arr[] : 数组首地址
size : 数组元素个数
indx : 需要查找的值
c. 函数功能 : 函数upper_bound()返回的在前闭后开区间查找的关键字的上界,返回大于val的第一个元素位置。
dfs代码:
#include "stdio.h"
#include "string.h"
char a[10],b[10];
int book[10],n;
void q(int s)
{
int i;
if(s==n)
{
for(i=0;i<n;i++)
printf("%c",a[i]);
printf("\n");
return;
}
for(i=0;i<n;i++)
{
if(book[i]==0)
{
a[s]=b[i];
book[i]=1;
q(s+1);
book[i]=0;
}
}
return;
}
int main ()
{
scanf("%s",b);
n=strlen(b);
q(0);
}