Next Permutation

本文详细介绍了如何实现下一个排列算法,并通过求解第K个排列问题加深理解。主要内容包括基本算法思路和进阶应用,适用于对排列组合算法感兴趣的读者。

初阶。

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation
of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending
order).
The replacement must be in-place, do not allocate extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the
right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1


#include <iostream>
#include <vector>
using namespace std;

/*
思路:
1.从后向前,找到第一个违反升序的元素(下降沿)。
2.从后向前,找到第一个比下降沿大的元素,作为交换元素。
3.交换两个元素。
4.反转下降沿后面所有的元素
*/

class solution{
public:
	void nextPermutation(vector<int> &num)
	{
		if(num.size() < 2)
			return;
		int i = num.size() - 2;
		while(i > 0 && num[i] > num[i+1])
			i--;

		//如果从后到前是升序,无可选方案。选择从前到后升序排列,reverse即可。
		if(i == 0)
		{
			reverse(num.begin(),num.end());
			return;
		}

		//从后往前找,第一个比下降沿num[i]大的数,作为交换数
		int j = num.size() - 1;
		while(j > i && num[j] <= num[i])
			j--;

		//交换num[i]和num[j]
		swap(num[i],num[j]);

		//反转下降沿之后的数字
		reverse(num.begin()+i+1,num.end());
		return;
	}
};

void main()
{
	solution sol;
	int a[] = {5,4,7,5,3,2};
	vector<int> v1(a,a+6);
	sol.nextPermutation(v1);
	vector<int>::iterator iter;
	for(iter=v1.begin();iter!=v1.end();iter++)
	{
		printf("%d ",*iter);
	}
	printf("\n");
}



进阶。

The set [1,2,3,⋯,n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order, We get the following sequence (ie, for n = 3):
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
Note: Given n will be between 1 and 9 inclusive.

思路:求第K个排列,可以调k-1次的下一个排列。

void getKthPermutation(int n,int k)
	{
		vector<int> vec;
		for(int i=1;i<=n;i++)
		{
			vec.push_back(i);
		}

		//求第K个排列,只需计算k-1次下一个排列即可
		for(int i=0;i<k-1;i++)
		{
			nextPermutation(vec);
		}
		return;
	}



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值