LeetCode每日一题(60. 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 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)
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值