leetcode 之 Permutation Sequence

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.

如果有n个元素,第K个permutation是a1, a2, a3, .....   ..., an,那么a1是哪一个数字呢?

那么这里,我们把a1去掉,那么剩下的permutation为:a2, a3, .... .... an, 共计n-1个元素。 n-1个元素共同拥有(n-1)!组排列,那么这里就能够知道

设变量K1 = K-1
a1 = K1 / (n-1)!// 即a1是1~n中未使用过的第a1个元素,比如,刚開始时,若a1 = 1,则结果的第一个元素是2

同理,a2的值能够推导为

K2 = K1 % (n-1)!  //前面的a1*(n-1)!已经增加,所以要去掉
a2 = K2 / (n-2)!

。。。。。

K(n-1) = K(n-2) /2!
a(n-1) = K(n-1) / 1!

an = K(n-1)

class Solution {
public:
    string getPermutation(int n, int k) 
    {
    	int data[10];//保存阶层的值
    	bool hashUse[10];
    	memset(hashUse,false,sizeof(bool)*10);
    	int i,j;
    	data[0] = data[1] = 1;
    	for(i = 2;i <= n;++i)data[i] = data[i-1] * i;
    	k --;
    	string res;
    	for(i = n - 1;i >= 0;--i)
    	{
    		int value = k / data[i];
    		for(j = 1;j <= n;++j)//查找第value大且未使用过的值
    		{
    			if(!hashUse[j])value--;
    			if(value < 0)break;
    		}
    		hashUse[j] = true;
    		res += j + '0';
    		k %= data[i];
    	}
    	return res;
    }
};



原文地址:https://www.cnblogs.com/blfshiye/p/4358963.html