Permutation Sequence

时间:2023-03-08 16:29:52

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.

Note: Given n will be between 1 and 9 inclusive.

分析: 这道题目看似可以采用全排列的方式得到所有组合,之后排序筛选出第k个大小的组合,但是会超出时间,仔细考虑题目中只要求第k个大小的组合,假设n=4, k=7; 4个数共有4x3x2x1 24个组合,考虑排在第k=7的组合的第一个数,应该是2, 因为第一个数可能为1,2,3,4中的任何一个,每一个情况都有3x2x1 6种情况, 所以向上取整7/6 为2, 这样第一个数就可以确定了,第二个数的情况排除第一个数, 考虑1,3,4 中第 k-(k/6) 中第一个数就可以了,依次类推

class Solution {
public:
int factorial(int n){
if(n== || n==)
return ;
int res=;
for(int i =; i<=n;i++)
res*=i;
return res;
}
char helper(string& s, int& k){
int n = factorial(s.size()-);
int index = (k-)/n;
char res = s[index];
s.erase(index,);
k -= n*index;
return res;
}
string getPermutation(int n, int k) {
string str = string("").substr(,n);
string res(n,' ');
for(int i=; i<n; i++)
res[i] =helper(str,k);
return res;
}
};