# \[46]\[中等]\[回溯] 全排列

## 题目描述

[46. 全排列](https://leetcode-cn.com/problems/permutations/)

给定一个 没有重复 数字的序列，返回其所有可能的全排列。

示例:

```
输入: [1,2,3]
输出:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]
```

## 解题思路

列举全部排列, 需要使用回溯的方法, 使用DFS的思路, 将元素逐个放入当前列表中, 直到备选列表中元素为空, 说明所有的元素都已经被使用, 从而得到了一种排列情况. 抛弃掉尾部的元素向上回溯, 探索另一种选择对应的情况.

由于列表中的元素没有重复值, 因此不需要考虑结果的重复问题.

```python
class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        results = []

        def dfs(path, residual):
            if len(residual) == 0:
                results.append(path[:])

            for i, num in enumerate(residual):
                path.append(num)
                dfs(path, residual[:i] + residual[i + 1:])
                path.pop()

        dfs([], nums)
        return results
```


---

# 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://kerasnoone.gitbook.io/garnet/suan-fa/hui-su/46-quan-pai-lie.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.
