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;
    }
};

Permutation Sequence - LeetCode

解法二:参考Grandyang的博客

小结

  • 全排列问题的变种

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-07-27
  • 2022-02-21
  • 2021-07-14
  • 2022-01-13
猜你喜欢
  • 2021-12-13
  • 2021-07-28
  • 2021-11-08
  • 2021-06-25
  • 2021-12-17
  • 2021-12-14
相关资源
相似解决方案