leetcode 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 (ie, for n = 3):

  1. "123"
  2. "132"
  3. "213"
  4. "231"
  5. "312"
  6. "321"

Given n and k, return the kth permutation sequence.


开始的思路就是求所有排列组合,按照字符序排序后输出第k个,不出所料,果然超时。。。

搜了别人的思路,有以下理解:

如果最终结果是"a1,a2,a3...an",那么我们要做的就是从第一位n1开始逐个确认n2、n3...直到得到第k个字符串组合

 n个字符(假设如此题中不重复)的排列共有n!个
 以第一个字符a1为例,不管a1,后面的n-1(即a2、a3...an)个字符的所有组合为(n-1)!,那么对于所有字符位于第一个的位置,均对应一个(n-1)!个组合 ----即n! = n*(n-1)!个组合
 第二个字符a2,如果确定第一个和第二个字符是哪一个,共有(n-2)!个组合 ----即n! =(A2/n)*(n-2)!个组合,依次类推。
 想要找第K个字符串组合中第一个字符是哪个,就要先计算 第K个字符串组合位于哪个字符对应的(n-1)!中,即K/(n-1)!个字符位于组合的第一位, 问题规模就缩小为找第(K-[K/(n-1)!] * (n-1)!)个长度为n-1的n-1个字符的组合

 要找第二个就要计算排除确定的第一个字符的n-1个字符集中,第K - [K/(n-1)!] * (n-1)!个组合再哪个字符对应的(n-2)!中。依次类推即可得到最终第K个组合。

代码如下:

</pre></p><p><pre name="code" class="cpp">class Solution {
public:
    string getPermutation(int n, int k) {
    	if(n<=0 || k<=0)
    		return NULL;
    	string result;
    	string s(n,'0');
    	int i, j, find, fac;
    	for(i=0;i<n;++i)
    		s[i] += i+1;
    	j = n-1;
    	k--;//题目中k从1开始,此方法是从0开始,故在此减一
    	while(j>=0)
    	{
    		fac = getNFactorial(j);
    		find = k/fac;
    		result += s[find];
    		adjust(s, find,j);
    		k = k-find*fac;
    		--j;
    	}
    	return result;
    }
    static int getNFactorial(int n)
    {
    	int result = 1;
    	for(int i=2;i<=n;++i)
    		result *= i;
    	return result;
    }
    static void adjust(string &s, int find, int n)
    {
    	for(int i=find;i<n;++i)
    		s[i] = s[i+1];
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值