STL的排列函数及字符串的排序方法
next_permutation(a,a+n); a代表数组的头地址,a+n代表数组的长度。
运用该函数,a数组将变成原排列的下一个排列。
与之相反的函数为prev_permutation(a,a+n);
#include <bits/stdc++.h> using namespace std; typedef long long LL; int f(int n) { int sum = 1; for(int i = 2; i <= n; i++) sum *= i; return sum; } int main() { //freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); int a[10]; int n; scanf("%d",&n); for(int i = 1; i <= n; i++) { a[i] = i; } for(int i = 1; i <= f(n); i++) { for(int j = 1; j <= n; j++) cout << a[j]; next_permutation(a+1,a+n+1); //prev_permutation(a+1,a+n+1); cout << endl; } return 0; }
上面是int型,下面的char型和string型的写法
第一行为输入,后面几行为输出,上题的整型输出类似
#include <bits/stdc++.h> using namespace std; typedef long long LL; int f(int n) { int sum = 1; for(int i = 2; i <= n; i++) sum *= i; return sum; } int main() { //freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); string b; //char a[100]; cin >> b; //scanf("%s",a); sort(b.begin(), b.end()); //sort(a, a+stlen(a)); for(int j = 1; j <= f(b.length()); j++) {// f(strlen(a)) cout << b << endl; // printf("%s\n",a); next_permutation(b.begin(),b.end()); // next_permutation(a, a+strlen(a)); } return 0; }