leetcode: 60. 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 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"

思路

可以发现规律是:从高位到低位 数字变的速度逐渐下降。第0位数,每隔 (n-1)! 次变一次;第1位数,每 (n-2)! 变一次。

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
            

 

发布了45 篇原创文章 · 获赞 1 · 访问量 3361

猜你喜欢

转载自blog.csdn.net/qq_22498427/article/details/104568448