Permutation Sequence - LeetCode

Posted 真子集

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Permutation Sequence - LeetCode相关的知识,希望对你有一定的参考价值。

题目链接

Permutation Sequence - LeetCode

注意点

  • n >= 1 && n <= 9
  • k >= 1 && k <= n!

解法

解法一:Next Permutation - LeetCode用这道题的函数,生成第n个序列,再转成字符串。效率不高

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int n = nums.size(),i = n-2,j = n-1;
        while(i >= 0 && nums[i] >= nums[i+1]) i--;
        //cout << i;
        if(i >= 0)
        {
            while(nums[j] <= nums[i]) j--;
            swap(nums[i],nums[j]);
        }
        reverse(nums.begin()+i+1,nums.end());
    }
    string getPermutation(int n, int k) {
        string ret ="";
        vector<int> nums;
        for(int i = 0;i < n;i++)
        {
            nums.push_back(i+1);
        }
        while(k > 1)
        {
            k--;
            nextPermutation(nums);
        }
        for(int i = 0;i <n ;i++)
        {
            ret += to_string(nums[i]);
        }
        return ret;
    }
};

解法二:参考Grandyang的博客

小结

  • 全排列问题的变种

以上是关于Permutation Sequence - LeetCode的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode31 Next Permutation and LeetCode60 Permutation Sequence

LeetCode(60):Permutation Sequence

LeetCode: 60. Permutation Sequence(Medium)

Permutation Sequence

60. Permutation Sequence

Permutation Sequence