LeetCode-60. Permutation Sequence [C++][Java]

LeetCode-60. Permutation Sequenceicon-default.png?t=M0H8https://leetcode.com/problems/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:

  1. "123"
  2. "132"
  3. "213"
  4. "231"
  5. "312"
  6. "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!

解题思路

康托展开_百度百科康托展开是一个全排列到一个自然数的双射,常用于构建哈希表时的空间压缩。 康托展开的实质是计算当前排列在所有由小到大全排列中的顺序,因此是可逆的。https://baike.baidu.com/item/%E5%BA%B7%E6%89%98%E5%B1%95%E5%BC%80/7968428

【C++】

class Solution {
public:
    string getPermutation(int n, int k) {
        vector<int> factorial(10);
        factorial[0] = 1;
        for (int i = 1; i < factorial.size(); ++i) {
            factorial[i] = factorial[i-1] *(i);
        }
        k--;
        string num = "123456789";
        string res;
        while (n--) {
            int num_loc = k/factorial[n];
            res += num[num_loc];
            k %= factorial[n];
            num.erase(num_loc,1);
        }
        return res;
    }
};

减少一点空间压力

class Solution {
public:
    string getPermutation(int n, int k) {
        vector<int> numbers;
        int fact = 1;
        for(int i=1;i<n;i++){
            fact *= i;
            numbers.push_back(i);
        }
        numbers.push_back(n);
        k--;
        string res = "";
        while(true){
            res += to_string(numbers[k/fact]);
            numbers.erase(numbers.begin()+k/fact);
            if(numbers.empty()){
                break;
            }
            k = k%fact;
            fact = fact/numbers.size();
        }
        return res;
    }
};

【Java】

class Solution {
    public String getPermutation(int n, int k) {
        String res = "";
        List<Integer> num = new LinkedList<>();
        int[] fac = new int[10];
        fac[0] = 1;
        for (int i=1; i<=n; i++) {
            fac[i] = fac[i - 1] * i;
            num.add(i);
        }
        k--;
        while (n-- > 0) {
            int index = k / fac[n];
            k %= fac[n];
            res += num.get(index);
            num.remove(index);
        } 
        return res;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

贫道绝缘子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值