> For the complete documentation index, see [llms.txt](https://dfine.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dfine.gitbook.io/leetcode/46.permutations.md).

# 46.Permutations

**46.Permutations**

难度:Medium

> Given a collection of distinct integers, return all possible permutations.

Example:

```
Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]
```

采用回溯法，想将每一位放在第一位，然后对于剩下的，将每一位放在第二位，一直循环下去。

```
class Solution {
vector<vector<int>>res;
void traceback(int n, int step)
{
    if(step == n) return;
    int len=res.size();
    for(int i=0;i<len;i++)
    {
        for(int j=step+1;j<n;j++)
        {
            vector<int> tmp(res[i]);
        swap(res[i][step],res[i][j]);
        res.push_back(tmp);
        }
    }
    traceback(n,step+1);
}
public:
    vector<vector<int>> permute(vector<int>& nums) {
        res.push_back(nums);
        traceback(nums.size(), 0);
        return res;
    }
};
```

> 执行用时 :12 ms, 在所有 C++ 提交中击败了98.71%的用户\
> 内存消耗 :9.7 MB, 在所有 C++ 提交中击败了29.71%的用户


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://dfine.gitbook.io/leetcode/46.permutations.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
