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 for n = 3:
“123”
“132”
“213”
“231”
“312”
“321”
Given n and k, return the kth permutation sequence.
Example 1:
Input: n = 3, k = 3
Output: “213”
Example 2:
Input: n = 4, k = 9
Output: “2314”
Example 3:
Input: n = 3, k = 1
Output: “123”
Constraints:
- 1 <= n <= 9
- 1 <= k <= n!
第 n-th 位的取值应为(k / (n-1)!) + 1, 但是这(k / (n-1)!) + 1, 该数字可能已经在前面的位上使用过了, 所以我们要用一个 mask 来记录已用的数字, 实际我们要找的是第(k / (n-1)!) + 1 个未使用的数字。注意如果 k % (n-1) == 0, 我们就不需要+1, 直接找第 k / (n-1)!个未使用数字即可
impl Solution {
fn factorial(n: i32) -> i32 {
if n == 1 {
return 1;
}
n * Solution::factorial(n - 1)
}
fn rc(n: i32, k: i32, mut mask: i32, remain: i32) -> String {
if k == 0 {
return "".into();
}
if k == 1 {
let mut ans = String::new();
for i in 1..=n {
if mask & (1 << i) == 0 {
ans.push_str(&i.to_string());
}
}
return ans;
}
let mut m = k / Solution::factorial(remain - 1) - if k % Solution::factorial(remain - 1) == 0 { 1 } else { 0 };
let ori_m = m;
let mut s = String::new();
for i in 1..=n {
if mask & (1 << i) > 0 {
continue;
}
if m == 0 {
s = i.to_string();
mask |= 1 << i;
break;
}
m -= 1;
}
let next = Solution::rc(n, k - ori_m * Solution::factorial(remain - 1), mask, remain - 1);
s.push_str(&next);
s
}
pub fn get_permutation(n: i32, k: i32) -> String {
Solution::rc(n, k, 0, n)
}
}