Saturday, May 18, 2013

Leetcode: Permutation Sequence in C++



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"
  1. "132"
  1. "213"
  1. "231"
  1. "312"
  1. "321"


Given n and k, return the kth permutation sequence.
Note: Given n will be between 1 and 9 inclusive.

Solution:
string getPermutation(int n, int k) {
        string result;
        vector<int> num(n);
        int total = 1;
        for(int i=0;i<n;i++)
        {
            num[i] = i+1;
            total *= i+1;
        }
        int q;
        for(int i=n;i>=1;i--)
        {
            total = total/i;
            q = (k-1)/total;
            k = k - q*total;
            result+='0'+num[q];
            num.erase(num.begin()+q);
        }
        return result;
    }

No comments:

Post a Comment