Given a collection of numbers, return all possible permutations.
For example,
[1,2,3]
have the following permutations:
[1,2,3]
, [1,3,2]
, [2,1,3]
, [2,3,1]
, [3,1,2]
, and [3,2,1]
.
void DFS(vector<vector<int> > &ans, vector<int> &vec, int n, int step)
{
if (step == n)
{
ans.push_back(vec);
}
else
{
for (int i = step; i < n; ++i)
{
swap(vec[step], vec[i]);
DFS(ans, vec, n, step + 1);
swap(vec[step], vec[i]);
}
}
}
vector<vector<int> > permute(vector<int> &num)
{
vector<vector<int> > ans;
int size = num.size();
DFS(ans, num, size, 0);
return ans;
}