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(起始地址, 终点位置); // 执行一次可以更改一次数组的内容,即改变至下一种排列
相关推荐
apcipot_rain14 小时前
C++转Java日记(05)
java·开发语言·c++
apcipot_rain1 天前
C++转Java日记(04)
java·开发语言·c++
NEFU_Jyj1 天前
牛客周赛R168
算法
WL学习笔记1 天前
vector模拟实现
c++
蜗牛一步步往上爬1 天前
第十六章 C++语言在深度学习中的应用
开发语言·c++·深度学习
likexuec1 天前
数据结构(2)
数据结构
Navigator_Z1 天前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode
wo_jack1 天前
C++ 入门笔记(十六):第16课 vector 模拟实现十问十答 —— 从三指针到迭代器失效
c++·后端·面试·stl·vector
D e re k ZH1 天前
C++ 标准库算法全景指南
数据结构·c++·算法