NO27、字符串的排列(经典题目,超级经典)
27、字符串的排列 经典题目,超级经典
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
输入描述:
输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。
示例1
输入
"ab"
返回值
["ab","ba"]
1、一个很奇特的函数next_permutation
返回全排列,使用方法如下所示,必须要进行排序才可以:
执行用时:52 ms, 在所有 C++ 提交中击败了91.01%的用户
内存消耗:17.9 MB, 在所有 C++ 提交中击败了100.00%的用户
vector<string> permutation(string s) {
if(s.size()==0) return vector<string>();
vector<string> result;
sort(s.begin(), s.end());
do {
result.push_back(s);
} while (next_permutation(s.begin(),s.end()));
return result;
}
#include <stdio.h>
#include <algorithm>
using namespace std;
int main(){
int n;
while(scanf("%d",&n)&&n){
int a[1000];
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
}
sort(a,a+n);
do{
for(int i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
}while(next_permutation(a,a+n));
}
return 0;
}
例如输入
3
1 0 2
如果有sort()
输出为
0 1 2
0 2 1
1 0 2
1 2 0
2 0 1
2 1 0
若无
则输出为
1 0 2
1 2 0
2 0 1
2 1 0
发现函数next_permutation()是按照
剩余60%内容,订阅专栏后可继续查看/也可单篇购买
带你刷完67道剑指offer 文章被收录于专栏
- 本专栏汇集了67道剑指offer的一些精妙解法,不少题有5-6种解法之多,有些题目二刷三刷的解法也不一样。 - 本专栏帮助我拿到6个互联网大厂offer,最终圆梦字节跳动公司。
顺丰集团工作强度 381人发布