Monday, October 14, 2013

Permutation Sequence [Leetcode]

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: find the mathematical pattern.

class Solution {
public:
    string getPermutation(int n, int k) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        string ret;
        
        int f = 1;
        for(int i=1; i<n; ++i) f*=i; //f is (n-1)!

        if(n<=0 || k>f*n || k<1) return ret;

        vector<int> num(n, 0); //for storing 1, 2, ..., n
        for(int i=0; i<n; ++i) num[i] = i+1;

        k--; //convert k-th to (k-1)-th in terms of index
        int cur = n-1;
        while(cur>=0){
            int index = k/f;
            ret.push_back(num[index]+'0');
            num.erase(num.begin()+index);
            k=k%f;
            f = (cur>0?f/cur:1);
            cur--;
        }
        return ret;
    }
};

No comments:

Post a Comment