LEETCODE: Permutation Sequence

来源:互联网 发布:时标网络计划特点 编辑:程序博客网 时间:2024/05/19 10:40

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.

如果有n个数,它排列的全部可能性是n!。所以看给出的k是多大了,看看可能性。k = a1 X n1! + a2 X n2! +... ai X ni!


class Solution {public:    string getPermutation(int n, int k) {        string result;        vector<int> base;        vector<int> digits;        for(int ii = 0; ii < n; ii ++) {            if(ii == 0) {                base.push_back(1);            }            else {                base.push_back(ii * base[ii - 1]);            }            digits.push_back(ii + 1);        }                for(int ii = n - 1; ii >= 0; ii --) {            int pos = (k - 1) / base[ii];            k = k - pos * base[ii];            result.push_back('0' + digits[pos]);            digits.erase(digits.begin() + pos);        }                return result;    }};


0 0
原创粉丝点击