1. 程式人生 > 實用技巧 >全排列 next_permutation()

全排列 next_permutation()

全排列

next_permutation()

在標頭檔案<algorithm>裡面有如下程式碼:

int a[];
do
{

}
while(next_permutation(a,a+n));

例子:

#include<bits/stdc++.h>
#include<set>
#include<vector>
#include<deque>
#include<map>
#include<queue>
using namespace std;
int main(){
    int n;
    cin
>>n; int * p = new int[n]; for (int i = 0; i < n; i++) { cin>>p[i]; } sort(p,p+n); do { for (int i = 0; i < n; i++) { cout<<p[i]<<" "; } cout<<endl; } while (next_permutation(p,p+n)); cout
<<endl; string s = "aba"; sort(s.begin(), s.end()); do { cout << s << '\n'; } while(next_permutation(s.begin(), s.end())); }

輸出:

3
1 2 3
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

aab
aba
baa

prev_permutation

例子

#include<bits/stdc++.h>
#include<set
> #include<vector> #include<deque> #include<map> #include<queue> using namespace std; int main(){ int n; cin>>n; int * p = new int[n]; for (int i = 0; i < n; i++) { cin>>p[i]; } sort(p,p+n,greater<int>()); do { for (int i = 0; i < n; i++) { cout<<p[i]<<" "; } cout<<endl; } while (prev_permutation(p,p+n)); cout<<endl; string s = "aba"; sort(s.begin(), s.end()); do { cout << s << '\n'; } while(prev_permutation(s.begin(), s.end())); }

輸出:

3
1 2 3
3 2 1
3 1 2
2 3 1
2 1 3
1 3 2
1 2 3

aab