[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.

Solution:

class Solution {
public:
    string getPermutation(int n, int k) {
    string ans = "";
    int *fact = new int[n + 1];
    int *data = new int[n + 1];
    fact[0] = 1;
    fact[1] = 1;
    for(int i = 1;i <= n;i++)
    {
        data[i] = i;
        fact[i] = fact[i - 1] * i;
    }

    int tmpK = k;
    for(int i = 1; i <= n;i++)
    {
        int ind = (tmpK - 1) / fact[n - i] + 1;
        tmpK = (tmpK - 1) % fact[n - i] + 1;
        int num_loc = 0;//current number's index in the remaining number list
        for(int j = 1;j <= n;j++)
        {
            if(data[j] != 0)
            {
                num_loc++;
                if(num_loc == ind)
                {
                    //this is the desire number for this location
                    ans += data[j] + '0';
                    data[j] = 0;
                    break;
                }
            }
        }
    }

    return ans;
    }
};
posted @ 2014-03-20 16:49  xchangcheng  阅读(202)  评论(0编辑  收藏  举报