LeetCode 0060. Permutation Sequence Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0060. Permutation Sequence

Description

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.

 

Example 1:

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

Example 2:

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

Example 3:

Input: n = 3, k = 1
Output: "123"

 

Constraints:

  • 1 <= n <= 9
  • 1 <= k <= n!

Solutions

Solution 1: Enumeration

We know that the set [1,2,..n] has a total of n! permutations. If we determine the first digit, the number of permutations that the remaining digits can form is (n-1)!.

Therefore, we enumerate each digit i. If k is greater than the number of permutations after the current position is determined, then we can directly subtract this number; otherwise, it means that we have found the number at the current position.

For each digit i, where 0 ≤ i < n, the number of permutations that the remaining digits can form is (n-i-1)!, which we denote as fact. The numbers used in the process are recorded in vis.

The time complexity is O(n^2), and the space complexity is O(n).

PythonJavaC++GoRustC#TypeScript
class Solution: def getPermutation(self, n: int, k: int) -> str: ans = [] vis = [False] * (n + 1) for i in range(n): fact = 1 for j in range(1, n - i): fact *= j for j in range(1, n + 1): if not vis[j]: if k > fact: k -= fact else: ans.append(str(j)) vis[j] = True break return ''.join(ans)(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !