【leetcode】 Permutation Sequence (middle)

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~n-1的阶乘,用另一个向量vec从小到大存1~n数字, 求第k位的话,我们用k-1(转为从0开始), 除以(n-1)!  其整数部分就是该位数字在vec的序号。之后在vec中删掉该数字,k2 %= (n-1)! 以此类推

class Solution {
public:
    string getPermutation(int n, int k) {
        vector<int> factorial(n, 1);
        vector<int> vec(n, 1);
        string ans;
        for(int i = 1; i < n; i++)
        {
            factorial[i] = factorial[i - 1] * i;
            vec[i] = i + 1;
        }
        if(k > factorial[n - 1] * n)
            return ans;

        int k2 = k - 1;
        for(int i = n - 1; i >= 0; i--)
        {
            int cur = k2 / factorial[i];
            char c[2];
            c[0] = '0' + vec[cur];
            c[1] = '\0';
            ans.append(c);
            vec.erase(vec.begin() + cur);
            k2 = k2 % factorial[i];
        }
        return ans;
    }
};

 

posted @ 2015-01-05 21:20  匡子语  阅读(197)  评论(0编辑  收藏  举报