C++自带的全排列函数 next_permutation()

函数原型
include<algorithm>
bool next_permutation(iterator strat,iterator end);
用法

若当前序列不存在下一个排列时,返回false,否则返回true。

  1. next_permutation按照字典序升序趋势,从当前状态向后做全排列。也即,如果导入2,1,3.函数只会从213开始向后找其他排列。如231,312,321。因此若要求某个序列的全排列,应当先升序排列,再导入。
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	int num[3]={3,1,2};
	do{
		cout << num[0] << num[1] << num[2] << endl;
	}while(std::next_permutation(num,num+3));
	
	return 0;
}

在这里插入图片描述

  1. 可以指定全排列区间(num,num+maxn)
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	string s = "123456";
	do{
		cout << s <<endl;
	}while(next_permutation(s.begin(),s.begin()+3));
	
	return 0;
}

在这里插入图片描述
如图所示: 指定了前3位进行全排列

  1. 可以指定进行全排列的方式next_permutation(start,end,cmp)。通过cmp指定。
发布了37 篇原创文章 · 获赞 1 · 访问量 2741

猜你喜欢

转载自blog.csdn.net/qq_39685968/article/details/104527433