Leetcode 60. Permutation Sequence

时间:2022-06-22
本文章向大家介绍Leetcode 60. Permutation Sequence,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://blog.csdn.net/Quincuntial/article/details/82260963

文章作者:Tyan 博客:noahsnail.com | CSDN | 简书

1. Description

2. Solution

class Solution {
public:
    string getPermutation(int n, int k) {
        string result;
        int factorial[n + 1] = {0};
        factorial[0] = 1;
        for(int i = 1; i <= n; i++) {
            factorial[i] = factorial[i - 1] * i;
        }
        vector<int> nums;
        for(int i = 1; i <=n; i++) {
            nums.push_back(i);
        }
        for(int i = n; i > 0; i--) {
            int remainder = k % factorial[i - 1];
            int quotient = k / factorial[i - 1];
            if(remainder) {
                quotient++;
            }
            result += to_string(nums[quotient - 1]);
            nums.erase(nums.begin() + quotient - 1);
            k %= factorial[i - 1];
            if(k == 0) {
                k = factorial[i - 1];
            }
        }
        return result;
    }
};

Reference

  1. https://leetcode.com/problems/permutation-sequence/description/