【LeetCode】60. 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):
"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.
我的方法从高位到低位逐位确定数字。
以图例n=3进行说明:
构建数组v={1,2,3}
确定最高位:
ind=(k-1)/2
注:分母2是指每个最高位持续的排列数。由于除了最高位之外还有n-1=2位,一共可以出现2!种排列。
ind指的是所求的第k个排列会落在哪一个最高位的覆盖范围内。
k==1,2时,ind==0,最高位为v[ind]==1
k==3,4时,ind==1,最高位为v[ind]==2
k==5,6时,ind==2,最高位为v[ind]==3
其余数位如上思路逐位确定。
注意:
1、k的更新。
2、vector<int> v的更新。
class Solution { public: string getPermutation(int n, int k) { string ret; vector<int> v(n); for(int i = 0; i < n; i ++) v[i] = i+1; while(n) { int ind = (k-1) / fac(n-1); ret += (v[ind]+'0'); k -= ind * fac(n-1); for(int i = ind+1; i < n; i ++) v[i-1] = v[i]; v.pop_back(); n --; } return ret; } int fac(int n) {//9! will not overflow int ret = 1; while(n) { ret *= n; n --; } return ret; } };