Monday, November 25, 2013

LeetCode Problem : Permutation Sequence

Problem


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.

Code

void gpt(int prod,int m,string& A,int k,int n)
{
    if(k == 1)
        return;
    while(k < prod){
        prod /= m;
        --m;
    }
    int pos = (k - 1)/prod;
    int end = n - m - 1;
    int factor = end + pos;
    char tmp = A[factor];
    for(int i = factor - 1;i >= end; --i)
        A[i + 1] = A[i];
    A[end] = tmp;
    k = k - pos*prod; 
    gpt(prod/m,m - 1,A,k,n);
}
string getPermutation(int n, int k) {
    // IMPORTANT: Please reset any member data you declared, as
    // the same Solution instance will be reused for each test case.
    int prod = 1;
    int j = n;
    while(j > 0){
        prod *= j;
        --j;
    }
    string result; 
    for(int i = 1; i <= n; i++)
        result += i + '0';
    if(prod == k){
        reverse(result.begin(), result.end());
        return result;
    }
    gpt(prod,n,result,k,n);
    return result;
}

No comments:

Post a Comment