Monday, April 20, 2015

[LeetCode] Permutation Sequence

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) 
    {
        string res;
        vector<int> num, f;
        int t = 1;
        for(int i=1;i<=n;t*=i++)
        {
            num.push_back(i);
            f.push_back(t);
        }
        
        int c, i = 1;
        while(res.length() < n)
        {
            int p = k%f[n-i];
            if(p == 0) c = (k/f[n-i]) -1; 
            else c = (k/f[n-i]);
            k -= c*f[n-i];
            res += num[c] + '0';
            num.erase(c + num.begin());
            i++;
        }
        return res;
    }
};