算法学习

算法题--给定数字n, 求第k个全排列

2020-04-16  本文已影响0人  岁月如歌2020
image.png

0. 链接

题目链接

1. 题目

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:

"123"
"132"
"213"
"231"
"312"
"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"

2. 思路1:递归

[1,2,3,4]的全排列可以写出:

1 --> (1, 2, 3, 4)
2 --> (1, 2, 4, 3)
3 --> (1, 3, 2, 4)
4 --> (1, 3, 4, 2)
5 --> (1, 4, 2, 3)
6 --> (1, 4, 3, 2)
7 --> (2, 1, 3, 4)
8 --> (2, 1, 4, 3)
9 --> (2, 3, 1, 4)
10 --> (2, 3, 4, 1)
11 --> (2, 4, 1, 3)
12 --> (2, 4, 3, 1)
13 --> (3, 1, 2, 4)
14 --> (3, 1, 4, 2)
15 --> (3, 2, 1, 4)
16 --> (3, 2, 4, 1)
17 --> (3, 4, 1, 2)
18 --> (3, 4, 2, 1)
19 --> (4, 1, 2, 3)
20 --> (4, 1, 3, 2)
21 --> (4, 2, 1, 3)
22 --> (4, 2, 3, 1)
23 --> (4, 3, 1, 2)
24 --> (4, 3, 2, 1)

从中可以看出

可见,满足典型的递归规律, 详细如下所示:

3. 代码

# coding:utf8
from typing import List


class Solution:
    def find(self, nums: List[int], k: int, multi: int, results: List[str]):
        if len(nums) == 0:
            return
        if len(nums) == 1:
            results.append(chr(ord('0') + nums[0]))
            nums.pop(0)
            return
        else:
            head_idx = (k - 1) // multi
            results.append(chr(ord('0') + nums.pop(head_idx)))
            k = k % multi
            multi = multi // len(nums)
            self.find(nums, k, multi, results)

    def getPermutation(self, n: int, k: int) -> str:
        multi = 1
        for i in range(1, n):
            multi *= i

        nums = list(range(1, n + 1))
        results = list()
        self.find(nums, k, multi, results)
        return ''.join(results)


solution = Solution()
print(solution.getPermutation(3, 3))
print(solution.getPermutation(4, 9))

输出结果

213
2314

4. 结果

image.png
上一篇 下一篇

猜你喜欢

热点阅读