Permutation Sequence

来源:互联网 发布:淘抢火车票软件 编辑:程序博客网 时间:2024/05/01 07:35

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.

class Solution:    # @return a string    def getPermutation(self, n, k):        k -= 1        ret = ''        product = [1 for i in range(n+1)]         for i in range(1,n+1):            product[i]=product[i-1]*i            char_set = [str(i) for i in range(1,n+1)]        index = n-1        for i in range(n-1,-1,-1):            _char = char_set[k/product[index]]            ret += _char            char_set.remove(_char)            if i!=0:                k %= product[index]                index-=1        return ret                                         


0 0