Make writing a habit together! This is the fifth day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.

preface

Our community will continue to add Yi Gu (Netflix growth hacker, author of “The Way to Interview for iOS”, ACE professional fitness coach. Swift algorithm solution sorted into text version to facilitate everyone to learn and read.

We have updated 59 issues of LeetCode algorithm so far, and we will keep the update time and progress (Monday, Wednesday, Friday 9:00 am release). The content of each issue is not much, we hope you can read it on your way to work, there will be a great improvement in long-term accumulation.

Short step, no thousands of miles; No small streams, no rivers and seas, Swift community with you forward. If you have suggestions and comments welcome to leave a message at the end of the article, we will try our best to meet your needs.

Difficulty level: Difficult

1. Describe

Give the set [1,2,3… n] in which all elements have n! Kind of arrangement.

All permutations are listed in order of size and marked one by one. When n = 3, all permutations are as follows:

  1. "123"
  2. "132"
  3. "213"
  4. "231"
  5. "312"
  6. "321"

Given n and k, return the KTH permutation.

Example 2.

Example 1

Input: n = 3, k = 3Copy the code

Example 2

Input: n = 4, k = 9Copy the code

Example 3

Input: n = 3, k = 1 Output: "123"Copy the code

Constraints:

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

3. The answer

class PermutationSequence {
    func getPermutation(_ n: Int._ k: Int) -> String {
        var numbers = [1.2.3.4.5.6.7.8.9]

        var factorial = 1
        for i in 1 ..< n {
            factorial * = i
        }

        var result = ""
        var k = k
        var divisor = n - 1

        for i in 0 ..< n {
            for (index, number) in numbers.enumerated() {
                if k > factorial {
                    k - = factorial
                } else {
                    result + = "\(number)"
                    numbers.remove(at: index)
                    break}}if divisor > 1 {
                factorial / = divisor
                divisor - = 1}}return result
    }
}
Copy the code
  • Main idea: iterate and change the array from the last to the first.
  • Time complexity: O(n^2)
  • Space complexity: O(1)

Leetcode-swift is a repository for solving problems of this algorithm

Click to go to LeetCode practice

About us

We are jointly maintained by Swift enthusiasts. We will share technical content based on Swift combat, SwiftUI and Swift foundation, as well as collect excellent learning materials.