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]
.
class Solution {
public:
vector<vector<int> > permute(vector<int> &num) {
vector<int> temp;
vector<int> visited(num.size(), 0);
dfs(num, 0, temp, visited);
return result;
}
private:
vector<vector<int> > result;
void dfs(vector<int> &num, int index, vector<int> &cur, vector<int> &visited)
{
if(index == num.size())
{
result.push_back(cur);
}
else
{
for(int i = 0; i < num.size(); i++)
{
if(visited[i] == 1)
continue;
else
{
cur.push_back(num[i]);
visited[i] = 1;
dfs(num, index+1, cur, visited);
cur.pop_back();
visited[i] = 0;
}
}
}
}
};
Round 2:
class Solution {
public:
vector<vector<int> > permute(vector<int> &num) {
vector<int> cur;
vector<vector<int> > result;
dfs(num, cur, 0, result, num.size());
return result;
}
private:
void dfs(vector<int> &num, vector<int> &cur, int index, vector<vector<int> > &result, int size)
{
if(index == size)
{
result.push_back(cur);
}
for(int i = 0; i < num.size(); i++)
{
cur.push_back(num[i]);
num.erase(num.begin() + i);
dfs(num, cur, index+1, result, size);
int temp = cur.back();
cur.pop_back();
num.insert(num.begin()+i, temp);
}
}
};