LeetCode-Permutation Sequence

来源:互联网 发布:唱歌的软件 编辑:程序博客网 时间:2024/05/29 17:56

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.

Solution:

Code:

<span style="font-size:14px;">class Solution {public:    string getPermutation(int n, int k) {        vector<int> nums(n, 1);        int t = 1;        for (int i = 2; i <= n; ++i) {            nums[i-1] = i;            t *= i;        }        t /= n;        --k;        string result;        while (n > 1) {            int q = k/t;            k = k%t;            --n;            t = t/n;            result += '0'+nums[q];            nums.erase(nums.begin()+q);        }        result += '0'+nums[0];        return result;    }};</span>



0 0
原创粉丝点击