leetcode: 60. Permutation Sequence

topic

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

  • Given k will be between 1 and n! inclusive.

Example 1:

      Input: n = 3, k = 3
             Output: "213"

Example 2:

     Input: n = 4, k = 9
            Output: "2314"

Thinking

Can be found rule is: change from high to low speed digital decreased. ! 0 bits, every (n-1) times the first variant;! 1 bits, each (n-2) becomes one.

def getPermutation(self, n: int, k: int) -> str:
        ans = [0]*n
        nums = [i for i in range(1,n+1)]

        # n-1 的阶乘
        n_p = 1
        for i in range(1,n):
            n_p *= i

        # 从高位到低位安排数字
        for i in range(n-1):
            index = k // n_p + int(k%n_p>0)
            ans[i] = nums[index-1]
            nums.remove(nums[index-1])
            k = k % n_p
            n_p = n_p // (n-i-1)
        ans[n-1] = nums[-1]

        ans_str = ""
        for i in ans:
            ans_str += str(i)
        return ans_str
            

 

Published 45 original articles · won praise 1 · views 3361

Guess you like

Origin blog.csdn.net/qq_22498427/article/details/104568448
Recommended