LeetCode - #60 Permutation Sequence

Get into the habit of writing together! This is the 5th day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .

foreword

Our community will successively organize Gu Yi ( Netflix growth hacker, author of "The Way of the iOS Interview", ACE professional fitness coach. Weibo: @古除道长)'s Swift algorithm problem solutions are organized into text versions for everyone to learn and read.

We have updated 59 issues of the LeetCode algorithm so far, and we will keep the update time and progress ( released at 9:00 am on Monday, Wednesday, and Friday ). There will be a big improvement.

If you don't accumulate a small step, you can't go a thousand miles; if you don't accumulate a small stream, you can't make a river. The Swift community accompanies you to move forward. If you have suggestions and comments, please leave a message at the end of the article, we will try our best to meet your needs.

Difficulty Level: Difficult

1. Description

Gives a set [1,2,3,...,n]with all elements in a total n!of permutations.

List all arrangements in order of magnitude and mark them one by one. n = 3When , all arrangements are as follows:

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

Given nand k, return kthe permutation.

2. Example

Example 1

输入:n = 3, k = 3
输出:"213"
复制代码

Example 2

输入:n = 4, k = 9
输出:"2314"
复制代码

Example 3

输入:n = 3, k = 1
输出:"123"
复制代码

Restrictions:

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

3. Answers

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
    }
}
复制代码
  • Main idea: iterate and change the array from last to first.
  • Time Complexity: O(n^2)
  • Space Complexity: O(1)

Repository for the algorithm solution: LeetCode-Swift

Click to go to LeetCode practice

about us

We are jointly maintained by Swift enthusiasts. We will share the technical content centered on Swift combat, SwiftUI, and Swift foundation, and also organize and collect excellent learning materials.

Guess you like

Origin juejin.im/post/7084180290092367902