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_rain11 小时前
C++转Java日记(02)
java·开发语言·c++
杜 硕12 小时前
从零开始的C++生活——第七讲——02
开发语言·c++·生活
Rabitebla20 小时前
【Linux 底层原理】进程(十):进程等待详解---从僵尸进程到 wait、waitpid 与 status
linux·c++·笔记·学习·visual studio
西西弗Sisyphus1 天前
C++ 超时互斥锁(Timed Mutex):std::timed_mutex 与 std::unique_lock
c++
其实防守也摸鱼1 天前
个人学习 Pwn 思路:从基础到漏洞利用的进阶路径
大数据·前端·人工智能·chrome·算法·安全·网络安全
今天要早睡_1 天前
C++01_入门基础复习
开发语言·c++
Nuanyt1 天前
LeetCode Hot 100 链表专题(五)· 2 题(Java)
java·算法·leetcode·链表
Fuyo_11191 天前
C++ 运行时多态与虚函数机制全面剖析【面试重点】
开发语言·c++·面试
w_zero_one1 天前
递归算法(一)
java·开发语言·算法