next_permutation (全排列算法)的使用

本文介绍了C++标准库STL中的next_permutation()函数,该函数用于求数组的所有可能排列。通过两个示例展示了如何使用此函数,并提到了在数组元素顺序较为混乱的情况下可以先使用sort函数进行排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

next_permutation。

在C++的标准函数库STL中,next_permutation()函数用于求数列的全排列。

头文件:#include<algorithm>

std::next_permutation (在C语言中使用)

#include<stdio.h>
#include<algorithm>
int main(){
	int i;
	int count = 0;
	int a[3] = {1, 2, 4};
	do{
		for(i = 0; i < 3; i++){
			printf("%d ", a[i]);
		}
		printf("\n");
		count++;
	}while(std::next_permutation(a, a+3));
	printf("%d", count);
	return 0;
}
输出:


当数组 a 中的数字不是按从大到小的顺序排序时,改为a[3] = {3, 2, 4}

#include<stdio.h>
#include<algorithm>
int main(){
	int i;
	int count = 0;
	int a[3] = {3, 2, 4};
	do{
		for(i = 0; i < 3; i++){
			printf("%d ", a[i]);
		}
		printf("\n");
		count++;
	}while(std::next_permutation(a, a+3));
	printf("%d", count);
	return 0;
}

输出:



注:如果数组中的数据比较混乱时,可以用sort函数进行排序

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值