【leetcode】 Permutation Sequence (middle)

时间:2023-03-08 20:12:48
【leetcode】 Permutation Sequence (middle)

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.

思路:给定序号找排列的字符串,肯定不用一个一个求,根据序号来判断每一位上的数字。用一个向量存储 0~n-1的阶乘,用另一个向量vec从小到大存1~n数字, 求第k位的话,我们用k-1(转为从0开始), 除以(n-1)!  其整数部分就是该位数字在vec的序号。之后在vec中删掉该数字,k2 %= (n-1)! 以此类推

class Solution {
public:
string getPermutation(int n, int k) {
vector<int> factorial(n, );
vector<int> vec(n, );
string ans;
for(int i = ; i < n; i++)
{
factorial[i] = factorial[i - ] * i;
vec[i] = i + ;
}
if(k > factorial[n - ] * n)
return ans; int k2 = k - ;
for(int i = n - ; i >= ; i--)
{
int cur = k2 / factorial[i];
char c[];
c[] = '' + vec[cur];
c[] = '\0';
ans.append(c);
vec.erase(vec.begin() + cur);
k2 = k2 % factorial[i];
}
return ans;
}
};