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.
class Solution { public: string getPermutation(int n, int k) { vector<char> pers(n, '1'); int fact = n; for (int i=1; i<n; i++) { fact *= i; pers[i] = '1' + i; } k--; string ans; for (int i=0; i<n; i++) { fact /= (n-i); const int j = k / fact; k %= fact; ans.push_back(pers[j]); pers.erase(pers.begin()+j); } return ans; } };
在leetcode上,实际执行时间为5ms。
基本思路:
参照普通进制的方法,求出每位的权重,从高位到低位利用整除和取余求出每位的值。
区别为,此权重都是阶乘值,不像普通进制,为基数的各次幂。
时间: 2024-10-13 16:10:02