next_permutation()
2026-10-29 21:23:48
发布于:广东
C++ next_permutation() 函数用法
一、函数作用
next_permutation() 用于将一个序列变成字典序的下一个排列。
例如:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
这些排列按照字典序从小到大排列。
二、基本用法
需要包含头文件:
#include <algorithm>
对于普通数组:
next_permutation(a, a + n);
对于 vector:
next_permutation(a.begin(), a.end());
返回值:
true:成功生成下一个排列。false:当前已经是最后一个排列,此时序列会恢复成字典序最小的排列。
三、枚举所有排列
通常配合 do-while 循环使用。
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
int a[10];
for(int i = 0; i < n; i++) cin >> a[i];
sort(a, a + n);
do {
for(int i = 0; i < n; i++)
cout << a[i] << " ";
cout << '\n';
} while(next_permutation(a, a + n));
return 0;
}
注意:枚举全部排列之前,必须先将数组升序排序。 否则只能枚举当前排列之后的部分排列。
四、其他用法
1. 枚举上一个排列
prev_permutation(a, a + n);
作用与 next_permutation() 相反,生成字典序的上一个排列。
2. 只生成下一个排列
if(next_permutation(a, a + n)) {
cout << "存在下一个排列";
}
else {
cout << "已经是最后一个排列";
}
五、时间复杂度
- 单次调用:。
- 枚举全部排列:。
如果序列中存在重复元素,函数也可以正常使用,并且不会生成重复的排列。
总结: next_permutation() 适合在数据规模较小时枚举所有排列。竞赛中最常见的写法就是先 sort(),再使用 do-while 循环枚举。
这里空空如也


















有帮助,赞一个