您的位置:首页 > 产品设计 > UI/UE

Permutation Sequence leetcode

2014-09-12 10:51 369 查看
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个。这样时间复杂度会很高.

仔细想一下可以找到一下规律:

n个数的的第k个排列为:

a1, a2, a3,...an;

接下来我们一个一个数的选取,如何确定第一个数应该是哪一个呢?选取第一个数后剩下全排列的个数为(n-1)! 所以选取的第一个数应该为第

 K1 = k;

a1 = K1/(n-1)!位数字

同理当选完a1后只剩下n-1个数字,在确定第二个数应该选择哪个.

a2 = K2 / (n-2)!

K2 = K1 % (n-1)!

........

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

K(n-1) = k(n-2) % 2!

an = K(n-1)

代码:

class Solution {
public:
string getPermutation(int n, int k) {
vector<int> num(n,0);
string res;
int per = 1;
for(int i=0;i<n;i++) {
num[i] = i+1;
per *= (i+1);
}
//因为数组是从0到n-1的 所以基数从 0到k-1
k--;
for(int i=0;i<n;i++) {
per = per/(n-i);
int s = k/per;
res.push_back(num[s]+'0');
//选择一个数后重新构造剩下的数组
for(int j=s;j<n-1-i;j++) {
num[j] = num[j+1];
}
k = k%per;
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode