Wednesday, June 4, 2014

Leetcode (Python): 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:
    # @return a string
    def getPermutation(self, n, k):
        numberPermutations = []
        count = 1
        numberPermutations.append(count)
        for i in range(1, n):
            count *= i
            numberPermutations.append(count)
        numbers = []
        for i in range(1, n+1):
            numbers.append(i)
        solution=[]
        count = k-1
        for i in range(0,n):
            position = count//numberPermutations[n-i-1]
            count -= position * numberPermutations[n-i-1]
            element = numbers.pop(position)
            solution.append(str(element))
        return "".join(solution)

No comments :

Post a Comment