LeetCode:Permutation Sequence

problems:

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 (ie, for n = 3):

  1. "123"
  2. "132"
  3. "213"
  4. "231"
  5. "312"
  6. "321"

Given n and k, return the kth permutation sequence.

Note: Given n will be between 1 and 9 inclusive.

思路: 采用的是康托编码的逆向展开算法。

由于我们是从0开始计数,k -= 1;(k-1)

首先,初始化一个vecotr,nums中的元素依次为:1, 2, 3;

获取第一位数字:k / 2! = 1,第一个数字就是 2,同时,从vector中删除已经使用的元素,剩余数字:1,3,并且k = k % 2! = 0;

获取第二个数字:k / 1! = 0,第二个数字就是1,同时,从链表中删除已经使用的元素),vector剩余数字:3,

由于达到最后一位,不需要操作k了。 获取第三个(最后)数字:剩余元素3

最终三个数字为213。

class Solution {
    
public:
    string getPermutation(int n, int k) {
        vector<int> nums;
        vector<int> factors; //初始化为一个元素,初始化为1
        
        for(int i=0;i<n;i++)
        {
            nums.push_back(i+1);
            if(!i)
                factors.push_back(1);
            else
                factors.push_back(factors[i-1]*i);
        }
        
        string result;
        int position;
       for(int i=n-1;i>-1;i--)
       {
           position=(k-1)/factors[i];
           k = k - position * factors[i];
           result.push_back(nums[position]+48);  //其实最后一位可以不用操做k
           nums.erase(nums.begin()+position);
       }
        return result;
    }
};
原文地址:https://www.cnblogs.com/xiaoying1245970347/p/4571390.html