prev_permutation 和 next_permutation

P1706 全排列问题

首先介绍一下prev_permutation 和 next_permutation,先看stl库中对这两个函数的定义:

其中第一个为默认情况:升序,第二个需要传一个仿函数comp

next_permutation的意思是下一个排列,与其相对的是prev_permutation,即上一个排列。我们需要使用全排列的时候就可以直接使用这两个函数,方便又快捷。

他的作用能够将排列后的下一组表示出来,比如我们要输出1,2,3,4所有排列情况

我们附上代码 :(next_permutation需要升序)

int main()
{
	int n; cin >> n;
	vector<int> arr(n);
	for (int i = 1; i <= n; i++)
		arr[i - 1] = i;
	do
	{
		for (auto e : arr)
			cout << setw(5) << e;
		cout << endl;
	} while (next_permutation(arr.begin(), arr.end()));
	return 0;
}

同样的我们也可以用prev_permutation函数来解决问题:

int main()
{
	int n; cin >> n;
	vector<int> arr(n);
	for (int i = 1; i <= n; i++)
		arr[i - 1] = i;
	sort(arr.begin(), arr.end(), greater<int>());
	do
	{
		for (auto e : arr)
			cout << setw(5) << e;
		cout << endl;
	} while (prev_permutation(arr.begin(), arr.end()));
	return 0;
}

prev_permutation要求倒序(降序),即最后一种情况4,3,2,1。

一般情况我们只会在列举所有可能情况中使用这两个函数,因此只需要记住这两个用法即可:

  1. prev_permutation要求倒序,可输出所有排列组合情况
  2. next_permutation需要升序,可输出所有排列组合情况
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值