Permutation Sequence

题目描述:

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 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.
    Given k will be between 1 and n! inclusive.

Example 1:
Input: n = 3, k = 3
Output: "213"

Example 2:
Input: n = 4, k = 9

Output: "2314"

思路:最初的想法是不需要从第一种排列一直排到第k种排列,我们知道当有n个数时,其全排列个数为n!,每一个数字作为第一个数字的排列情况各有(n-1)!种,例如n为3时,1开头的排列共有2(也就是(3-1)!)种,2开头的排列共有2(也就是(3-1)!)种,3开头的排列共有2(也就是(3-1)!)种,我们通过k/2,就可以知道第k种排列是以哪个数字开头的,所以我们只排列该数字开头的情况,并取第k%2(也就是k%(3-1)!)种排列即可。


#include<cstdio>
#include<string>
#include<vector>
#include<algorithm>
using namespace std; 

int times;
void Permutation(vector<int>& result,vector<int> nums,int a,int k)
{
	if(a==nums.size())
	{
		times++;	    
		if(times==k)
			result.assign(nums.begin(),nums.end());			 
		return;
	}
	else
	{
		for(int i=a;i<nums.size();i++)
		{
			swap(nums[a],nums[i]);
			Permutation(result,nums,a+1,k); 
			if(times==k)
			    break;
		}
	} 
}
string getPermutation(int n, int k) 
{
	times = 0;
        //得到(n-1)! 
	int count = 1; 
	for(int i=2;i<n;i++)
	    count *= i;
	int begin = k/count;
	//下面对开头数字以及k的判断主要是对每个数字开头的最后一种排列情况做特殊处理 
	begin = k%count==0?begin:begin+1;
	k = k%count==0?count:(k%count);

	vector<int> nums;
	//直接构建begin开头的排列的第一种情况 
	nums.push_back(begin);
	for(int i=1;i<=n;i++)
		if(i!=begin) 
		    nums.push_back(i);    	
	
	vector<int> result; 
	Permutation(result,nums,1,k);
	   
	string str = "";
	//将vector<int>转化为字符串 
	for(int i=0;i<n;i++)
	{
	    char c = '0'+result[i];
	    str = str+c;
	} 
	return str;    
}
int main(){
	int n = 4;
	int k = 5;
	string result = getPermutation(n,k);
	printf("%s\n",result.c_str());
	return 0;
}
后来还在网上看见了一种可以说是这道题的 最佳解法,思路和我的很相似只不过我找到了第一个开头数字然后排列,而这种方法却用找第一个数字的方法找到了所有的数字。


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值