# 46. Permutations
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]
]
# Solution
Approach 1: DFS with Swap.
# Code (Python)
Approach 1:
# Code (C++)
Approach 1:
class Solution {
private:
vector<vector<int>> res;
void permute(vector<int>& nums, int head) {
if (head == nums.size())
{
res.push_back(nums);
return;
}
for (int i = head; i < nums.size(); ++i)
{
if (i > head)
std::swap(nums[head], nums[i]);
permute(nums, head + 1);
if (i > head)
std::swap(nums[head], nums[i]); // need to swap back.
}
}
public:
vector<vector<int>> permute(vector<int>& nums) {
permute(nums, 0);
return res;
}
};