C++ STL 快速实现全排列

目的

输入n个数,对这n个数进行全排列。

样例输入

3

3 2 1

样例输出

1 2 3

1 3 2

2 1 3

2 3 1

3 1 2

3 2 1

实现

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;

const int N = 10;


int main() {
	int n, a[N];
	cin >> n;
	for (int i = 1; i <= n; i++)
		cin >> a[i];
	sort(a + 1, a + n + 1);
	do {
		for (int i = 1; i <= n; i++) {
			if (i != 1)			
				cout << " ";
			cout << a[i];
		}
		cout << endl;
	} while (next_permutation(a + 1, a + n + 1));
	return 0;
}

利用STL库里的next_permutation函数实现数组或者容器的全排列。

cpp 复制代码
next_permutation(起始地址, 终点位置); // 执行一次可以更改一次数组的内容,即改变至下一种排列
相关推荐
电科_银尘1 小时前
【大模型算法与工程 15】手写Self-Attention:Q、K、V与缩放点积
算法
我不会插花弄玉2 小时前
13.多路转接epoll【由浅入深-网络】
网络·c++·epoll
郝学胜-神的一滴4 小时前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
秋天的怀念_David4 小时前
算法一千零一夜 · 第三十三夜 · 跳表
java·程序人生·算法
西西弗Sisyphus5 小时前
C++ explicit 关键字工程实践
开发语言·c++
Pniubi7 小时前
力扣21合并两个有序链表
算法·leetcode·职场和发展
AIgorithmGEEK7 小时前
std::unordered_map 与 std::unordered_set:接口、算法技巧与权衡 (速查)
c++·算法·哈希表·负载因子·桶·unordered_map·unordered_set
上海潭龙东海科技有限公司9 小时前
智慧堆场动态模型三维实时孪生重构智能管控
大数据·网络·数据库·算法·重构
一拳一个呆瓜9 小时前
【STL】头文件:<cmath>
c++·stl
草莓熊Lotso10 小时前
【C++ 基于微服务的即时通讯系统】ElasticSearch 用户数据管理实现
linux·数据库·c++·elasticsearch·微服务·架构