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(起始地址, 终点位置); // 执行一次可以更改一次数组的内容,即改变至下一种排列
相关推荐
_wyt0011 小时前
01背包问题详解
c++·背包dp
方便面不加香菜1 小时前
C++ 模板进阶
开发语言·c++
Wild_Pointer.2 小时前
高效工具实战指南:Procexp64进程资源管理器
c++·windows
cjr_xyi2 小时前
AT1202Contest_c binarydigit 题解
c语言·c++·算法
会周易的程序员2 小时前
Libnodave S7 通信库:架构设计与实现解析
linux·c++·物联网·架构·c·s7·工业协议
jinyishu_2 小时前
C++ 多态完全指南:从基础语法到底层原理
开发语言·c++·程序人生·面试
atunet3 小时前
从算法优化到系统加速的多层级思考7
算法
夜不会漫长3 小时前
数据结构:链表
数据结构·链表
Navigator_Z3 小时前
LeetCode //C - 1156. Swap For Longest Repeated Character Substring
c语言·算法·leetcode
Reart4 小时前
Leetcode 1143.最长公共子序列(720)
后端·算法