|
Problem Description:
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个排列,以n = 4,k = 17为例,数组src = [1,2,3,...,n]。 第17个排列的第一个数是什么呢:我们知道以某个数固定开头的排列个数 = (n-1)! = 3! = 6, 即以1和2开头的排列总共6*2 = 12个,12 < 17, 因此第17个排列的第一个数不可能是1或者2,6*3 > 17, 因此第17个排列的第一个数是3。即第17个排列的第一个数是原数组(原数组递增有序)的第m = upper(17/6) = 3(upper表示向上取整)个数。 第一个数固定后,我们从src数组中删除该数,那么就相当于在当前src的基础上求第k - (m-1)*(n-1)! = 17 - 2*6 = 5个排列,因此可以递归的求解该问题。 代码实现中注意一个小细节,就是一开始把k--,目的是让下标从0开始,这样下标就是从0到n-1,不用考虑n时去取余,更好地跟数组下标匹配。具体代码如下: class Solution {
public:
int fun(int n)
{
if(n<0)
return 0;
else if(n==0)
return 1;
else
return n*fun(n-1);
}
string getPermutation(int n, int k) {
string s;
int total=fun(n);
if(total
flag(n,0);
//因为数组是从0到n-1的,所以基数从0到k-1
--k;
for(int i=0;i
|