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(起始地址, 终点位置); // 执行一次可以更改一次数组的内容,即改变至下一种排列
相关推荐
不会就选b6 小时前
算法日常・每日刷题--<贪心>14
算法
初願致夕霞6 小时前
C++11:类型推导与完美转发复盘笔记
c++
小猪写代码6 小时前
C++中什么是类,什么是对象
c++
mmmmath_39 小时前
LeetCode.541.反转字符串II
数据结构·算法·leetcode
Navigator_Z9 小时前
LeetCode //MySQL - 1251. Average Selling Price
c语言·算法·leetcode
醇氧10 小时前
MySQL 8.0 系统表损坏与引擎转换故障排查实战
数据结构·算法
大熊背10 小时前
《Color constancy by characterization of illumination chromaticity》之色度色域最大化算法(二)
算法·白平衡·色度·色温
钓鱼的肝10 小时前
梳理(1-5)
c++·经验分享·笔记·算法·青少年编程
HZZD_HZZD11 小时前
CSDN_批发市场水电漏损归因算法LAM的原理与落地
嵌入式硬件·物联网·算法