c++ 全排列算法 c++ next_permutation用法

使用next_permutation生*排列需先排序,再用do-while循环遍历所有排列,该函数自动处理重复元素并按字典序生成,适用于小规模数据。

在 C++ 中生*排列,最常用的方法是使用标准库中的 next_permutation 函数。它属于 algorithm 头文件,能高效地按字典序生成下一个排列,非常适合枚举所有可能的排列情况。

next_permutation 基本用法

next_permutation 的作用是将当前序列重新排列为字典序中的下一个更大排列。如果存在下一个排列,函数返回 true;否则(即当前已经是最大字典序排列),返回 false,并将序列重置为最小字典序(即升序)。

函数原型如下:

bool next_permutation(Iterator first, Iterator last);

参数是容器的起始和结束迭代器,比如数组或 vector 的 begin() 和 end()。

生*排列的完整流程

要生成一个序列的所有全排列,必须先将元素排序(升序),这样才能从最小字典序开始,用 next_permutation 逐个遍历直到回到初始状态。

示例代码:

#include iostream>
#include
#include
using namespace std;

int main() {
vector nums = {1, 2, 3};
sort(nums.begin(), nums.end()); // 确保从小到大开始

do {
for (int num : nums) {
cout }
cout } while (next_permutation(nums.begin(), nums.end()));

return 0;
}

输出结果为 1 2 3 到 3 2 1 的所有排列,共 6 种。

处理重复元素的情况

当序列中有重复元素时,next_permutation 会自动跳过重复的排列,只生成不重复的结果。这是它的优点之一,无需手动去重。

例如:

vector chars = {'a', 'a', 'b'};
sort(chars.begin(), chars.end());
do {
cout } while (next_permutation(chars.begin(), chars.end()));

输出只有三种:aab, aba, baa。不会出现重复组合。

常见使用技巧与注意事项

  • 确保数据已排序,否则会遗漏部分排列。
  • 循环使用 do-while 而不是 while,避免漏掉第一个排列。
  • 适用于数组、vector、string 等支持随机访问迭代器的容器。
  • 时间复杂度为 O(n!×n),适合小规模数据(n ≤ 10 左右)。

基本上就这些。掌握 next_permutation 可以快速实现排列枚举,写算法题或暴力搜索时非常实用。不复杂但容易忽略排序这一步。