Leetcode: Permutation Sequence

来源:互联网 发布:淘宝宝贝排名工具 编辑:程序博客网 时间:2024/06/06 14:19

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.


class Solution {public:    string getPermutation(int n, int k) {        vector<int> table(n-1, 0);        vector<int> nums(n, 0);        string ret;        int i, c;        if (n == 1) return "1";        table[n-2] = 1;        for (i = n-3; i >= 0; i--) {            table[i] = table[i+1] * (n-1-i);        }        i = 1;        while(i < n) {            c = (k-1) / table[i-1];            k -= c * table[i-1];            c = pickNumber(nums, c+1);            ret.append(1, '0'+c);            ++i;            if (k == 0) break;        }                for (i = 0; i < n; i++) {            if (nums[i] == 0) {                ret.append(1, '0'+i+1);            }        }        return ret;    }private:    int pickNumber(vector<int> &nums, int n) {        int i = 0;        int k = 0;        while (i < nums.size()) {            if (nums[i] == 0) {                ++k;                if (k == n) {                    nums[i] = 1;                    return i+1;                }            }            ++i;        }        return nums.size()-1;    }};


0 0
原创粉丝点击