# 60 Permutation Sequence

## 60. [Permutation Sequence](https://leetcode.com/problems/permutation-sequence/description/)

## 1. Question

The set`[1,2,3,…,n]`contains a total ofn! unique permutations.

By listing and labeling all of the permutations in order,\
We get the following sequence (ie, forn= 3):

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

Given n and k, return the kth permutation sequence.

## 2. Implementation

**(1) Math**

思路 <https://leetcode.com/problems/permutation-sequence/discuss/22507/%22Explain-like-I'm-five%22-Java-Solution-in-O(n\\>)

```java
class Solution {
    public String getPermutation(int n, int k) {
        if (n <= 0 || k <= 0) {
            return "";
        }

        StringBuilder res = new StringBuilder();
        StringBuilder nums = new StringBuilder();

        for (int i = 1; i <= n; i++) {
            nums.append(i);
        }

        --k;
        int[] factorial = new int[n + 1];
        factorial[0] = 1;
        for (int i = 1; i <= n; i++) {
            factorial[i] = factorial[i - 1] * i;
        }

        for (int i = 1; i <= n; i++) {
            int index = k / factorial[n - i];
            res.append(nums.charAt(index));
            nums.deleteCharAt(index);
            k -= index * factorial[n - i];
        }
        return res.toString();
    }
}
```

## 3. Time & Space Complexity

**Math:** 时间复杂度O(n), 空间复杂度O(n)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://protegejj.gitbook.io/algorithm-practice/leetcode/backtracking/60-permutation-sequence.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
