`prev_permutation` 是 `
#include <algorithm>
#include <iostream>
using namespace std;
int main() {
int a[] = {3, 2, 1}; // 從最後一個排列開始
do {
for(int x : a) cout << x << ' ';
cout << '\n';
} while(prev_permutation(a, a+3));
// 輸出: 3 2 1, 3 1 2, 2 3 1, 2 1 3, 1 3 2, 1 2 3
}
sort(a, a+n); // 必須從升序開始
do {
// 處理當前排列 a
} while(next_permutation(a, a+n));
string s = "abc";
sort(s.begin(), s.end());
do {
cout << s << '\n';
} while(next_permutation(s.begin(), s.end()));
// 僅對前 k 個元素排列
while(next_permutation(a, a+k)) { ... }
bool cmp(char a, char b) {
if(tolower(a) != tolower(b)) return tolower(a) < tolower(b);
return a < b; // 大寫在小寫前
}
sort(ch, ch+len, cmp);
do {
puts(ch);
} while(next_permutation(ch, ch+len, cmp));
`prev_permutation`/`next_permutation` 是 C++ 標準庫中高效生成排列的工具,配合排序可遍歷全排列,支持自定義比較,是組合生成問題的利器。