5.全排列

全排列

一般全排列,可以使用搜索的方法完成,这里我们介绍其函数的实现方式。

1. next_permutation()函数

next.permutation函数用于生成当前序列下一个排列。它按照字典序对序列进行重新排列,如果存在下一个排列,则将当前序列更改为下一个排列,并返回 true;如果当前序列已经是最后一个排列,则将序列更改为第一个排列,并返回false。

#include <bits/stdc++.h>
using namespace std;
int main() {
	vector<int> nums = {1, 2, 3};
	cout << "Initial permutation: ";
	for(int num : nums) {
		cout << num << " ";
	} 
	cout << endl;	
	// 生成下一个排列
	while(next_permutation(nums.begin(), nums.end())) {
		cout << "next permutation: ";
		for(int num : nums) {
			cout << num << " ";	
		}
		cout << endl;
	}
	return 0;
}

输出结果

Initial permutation: 1 2 3
next permutation: 1 3 2
next permutation: 2 1 3
next permutation: 2 3 1
next permutation: 3 1 2
next permutation: 3 2 1

对于一个数组,如何实现字典序正序全排列?如下代码所示

#include <bits/stdc++.h>
using namespace std;

int main() {
	int a[] = {1, 2, 3};
	// 输出当前的序列 
	for(int i = 0; i < 3 ; i ++ ) {
		printf("%d ", a[i]);
	}
	cout << endl;
	while(next_permutation(a, a + 3)) { // 直接变成当前序列全排序的下一个序列, 首先输出的
		for(int i = 0; i < 3 ; i ++ ) { // 是123
			printf("%d ", a[i]);
		}
		cout << endl;
	} 
	return 0;
}

2. prev_permutation()函数

prev_permutation函数与next_permutation函数相反,它用于生成当前序列的上一个排列。它按照字典序对序列进行重新排列,如果存在上一个排列,则将当前序列更改为上一个排列,并返回true;如果当前序列已经是第一个排列,则将序列更改为最后一个排列,并返回false。

#include <bits/stdc++.h>
using namespace std;


int main() {
	vector<int> nums = {3, 2, 1};
	cout << "Initial permutation: ";
	for(int num : nums) {
		cout << num << " ";
	} 
	cout << endl;
	
	// 生成下一个排列
	while(prev_permutation(nums.begin(), nums.end())) {
		cout << "Previous permutation: ";
		for(int num : nums) {
			cout << num << " ";	
		}
		cout << endl;
	}
	return 0;
}

输出结果

Initial permutation: 3 2 1
Previous permutation: 3 1 2
Previous permutation: 2 3 1
Previous permutation: 2 1 3
Previous permutation: 1 3 2
Previous permutation: 1 2 3

对于一个数组,如何实现字典序倒序全排列?

#include <bits/stdc++.h>
using namespace std;

int main() {
	int a[] = {3, 2, 1};
	// 输出当前的序列 
	for(int i = 0; i < 3 ; i ++ ) {
		printf("%d ", a[i]);
	}
	cout << endl;
	while(prev_permutation(a, a + 3)) {
		for(int i = 0; i < 3 ; i ++ ) {
			printf("%d ", a[i]);
		}
		cout << endl;
	} 
	return 0;
}
  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值