用C++求全排列的几种方法

交换法

交换法的优点:不需要额外的标记数组,空间复杂度更低,代码更简洁。需要注意的是,这个方式生成的全排列并非是字典序。

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

int arr[10] = {0, 1, 2, 3, 4};

void dfs(int x) {
    if (x > 4) {
        for (int i = 1; i <= 4; i++) {
            cout << arr[i] << " ";
        }
        cout << endl;
        return;
    }

    for (int i = x; i <= 4; i++) {
        swap(arr[x], arr[i]);    // 交换当前位置和后续位置
        dfs(x + 1);              // 递归处理下一个位置
        swap(arr[x], arr[i]);    // 回溯,交换回来
    }
}

int main() {
    dfs(1);
    return 0;
}

标记数组法

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

int res[10],arr[10] = {0, 1, 2, 3, 4};
bool used[10];

void dfs(int x){
    if(x>4){
        for(int i=1;i<=4;i++)cout << res[i] << " ";
        cout << endl;
        return;
    }
    for(int i=1;i<=4;i++){
        if(!used[i]){
            used[i]=true;
            res[x]=arr[i];
            dfs(x+1);
            used[i]=false;
        }
    }
}

int main(){
    dfs(1);
}

结果对比

序号交换法生成顺序标记法生成顺序(字典序)
11 2 3 41 2 3 4
21 2 4 31 2 4 3
31 3 2 41 3 2 4
41 3 4 21 3 4 2
51 4 3 21 4 2 3
61 4 2 31 4 3 2
72 1 3 42 1 3 4
82 1 4 32 1 4 3
92 3 1 42 3 1 4
102 3 4 12 3 4 1
112 4 3 12 4 1 3
122 4 1 32 4 3 1
133 2 1 43 1 2 4
143 2 4 13 1 4 2
153 1 2 43 2 1 4
163 1 4 23 2 4 1
173 4 1 23 4 1 2
183 4 2 13 4 2 1
194 2 3 14 1 2 3
204 2 1 34 1 3 2
214 3 2 14 2 1 3
224 3 1 24 2 3 1
234 1 3 24 3 1 2
244 1 2 34 3 2 1

全排列的STL标准库实现

std::next_permutation 是 C++ 标准库 <algorithm> 头文件中的一个强大函数,用于按字典序(从小到大)生成一个序列的下一个排列。

函数原型

template< class BidirIt >
bool next_permutation( BidirIt first, BidirIt last );

// 也可以自定义比较规则
template< class BidirIt, class Compare >
bool next_permutation( BidirIt first, BidirIt last, Compare comp );

参数说明

first, last: 要生成排列的序列的起始和末尾迭代器(通常用 begin(), end())。
comp: 自定义的比较函数对象,用于定义“小于”的概念。

返回值

true: 如果成功生成下一个更大的排列。
false: 如果当前序列已经是最大的排列(即降序排列)。此时,函数会将序列重置为最小的排列(即升序排列)。

核心特性

会修改原序列:该函数是原地操作的,会直接改变传入的容器。
需要序列有序:为了生成所有排列,通常需要先对序列进行升序排序。
重复元素:函数能够正确处理序列中的重复元素,不会生成重复的排列。

应用于vector:

#include <iostream>
#include <vector>
#include <algorithm> // 包含 next_permutation

using namespace std;

int main() {
    vector<int> vec = {1, 2, 3};

    // 重要:先排序以确保从最小排列开始
    // sort(vec.begin(), vec.end()); 
    // 本例中 {1,2,3} 已经是最小排列,所以可省略排序

    cout << "All permutations of {1, 2, 3}:\n";
    
    do {
        for (int num : vec) {
            cout << num << " ";
        }
        cout << endl;
    } while (next_permutation(vec.begin(), vec.end())); 
    // 当 next_permutation 返回 false 时循环结束

    return 0;
}

应用于字符串:

#include <iostream>
#include <algorithm> // 包含 next_permutation
#include <string>

using namespace std;

int main() {
    string str = "abc";

    // 同样,如果需要所有排列,应先排序
    // sort(str.begin(), str.end());
    
    cout << "All permutations of \"abc\":\n";
    do {
        cout << str << endl;
    } while (next_permutation(str.begin(), str.end()));

    return 0;
}

处理有重复元素的序列

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
    vector<int> vec = {1, 1, 2};

    // 必须先排序!
    sort(vec.begin(), vec.end());

    cout << "All permutations of {1, 1, 2}:\n";
    do {
        for (int num : vec) {
            cout << num << " ";
        }
        cout << endl;
    } while (next_permutation(vec.begin(), vec.end()));

    return 0;
}

遍历所有排列:

#include <algorithm>
#include <vector>

std::vector<int> data = {3, 1, 4, 1, 5}; // 未排序的序列

// 1. 首先必须排序!
std::sort(data.begin(), data.end());

// 2. 使用 do-while 循环
do {
    // 处理当前的排列,例如打印它
    // for (auto x : data) { ... }
} while (std::next_permutation(data.begin(), data.end()));

标签: c++

移动端可扫我直达哦~

推荐阅读

thumbnail 2025-09-05

P1088 [NOIP 2004 普及组] 火星人与康托展开

变进制数我们的目标是把全排列转化成一个变进制数,以方便我们进行加法。对于第 i 根手指,它有 n−i+1 种选择,根据位值原理,要想让每个数对应一个全排列,就要让这一位数是 n−i+1 进制的。那么,整个过程分为三步:将火星数变成变进...

少儿编程 c++

thumbnail 2025-08-30

关于 c++ 中的 unique() 函数

unique() 是C++标准库中一个非常实用的算法,用于去除相邻的重复元素。使用它之前需要先引入必须包含的头文件:#include<algorithm>基本语法#include <algorithm> // ...

少儿编程 c++

thumbnail 2025-08-30

lower_bound 为什么结果要减去数组名

lower_bound 结果减去数组名是为了将返回的迭代器(指针)转换为数组下标(索引)。lower_bound 返回的是一个迭代器(对于数组来说就是指针),指向找到的元素位置。int arr[] = {10, 20, 30, 40,...

少儿编程 c++

thumbnail 2025-08-25

c语言中的 fstream 与 freopen 区别

fstream(C++风格)和 freopen(C风格)都是用于文件输入/输出的工具,但它们在设计理念、用法和灵活性上有根本性的区别。核心概览 特性fstream (C++)freopen (C)所属语言标准C++C编程范式面向对象 ...

少儿编程 c++

thumbnail 2025-08-24

c++面向对象--类的学习笔记

在学习类之前,相信很多人跟博主一样,已经学习过结构体。在 C++ 中,struct 和 class 的区别非常小,几乎只是默认访问权限的不同。默认访问权限/继承权限:struct 的默认成员访问权限和默认继承方式都是 public。c...

少儿编程 c++

thumbnail 2025-08-23

栈上数组和堆上数组

对比表格 特性栈上数组堆上数组内存位置栈内存堆内存声明方式int arr[10];int* arr = new int[10];生命周期所在作用域结束自动释放需要手动delete[]释放大小确定编译时确定(必须是常量)运行时确定(可以...

少儿编程 c++

thumbnail 2025-08-03

方格取数与传纸条-双人网格路径问题

24年在洛谷刷刷题,遇到过一个双人路径问题,P1004 [NOIP 2000 提高组] 方格取数,题解的4维数组对于博主这样一个菜鸟,实在难以理解,于是就搁置了。然而25年的时候又遇到了P1006 [NOIP 2008 提高组] 传纸...

少儿编程 c++

thumbnail 2025-07-16

二分查找无解为什么用 n+1

二分查找是一种在有序数组中查找特定元素的高效算法。它的基本思想是通过不断地将查找范围减半来快速定位目标元素。然而,在某些情况下,二分查找可能无法找到目标元素,这时就需要处理无解的情况。关于二分查找无解时使用 n+1 的原因,可以从以下...

少儿编程 c++

thumbnail 2025-07-16

关于后缀和的哨兵值

在二分查找结合后缀和(Prefix Sum / Suffix Sum)的问题中,哨兵值(Sentinel Value) 的作用是:处理边界情况(如所有元素都不满足条件时)。防止数组越界访问(如 sum[-1] 或 sum[n+1])。...

少儿编程 c++

thumbnail 2025-02-13

CSP-J/S认证有年龄限制吗

刚在朋友圈看到这则通知,去官网确认了一下属实,个人觉得这是好事,童年该有童年应有的样子。学习计算机科学有益于培养青少年的逻辑思维及用计算机解决实际问题的能力。但是,这需要一定的基础和认知能力,并非越早越好。近年来,参加CCF非专业级软...

少儿编程 c++