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].
code: STL method and recursion method.
class Solution {
public:
vector<vector<int> > permute(vector<int> &num) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<vector<int> > res;
if(num.size() == 0)
return res;
//vector<int> tmp;
sort(num.begin(),num.end());
res.push_back(num);
while( next_permutation(num.begin(),num.end()) )
{
res.push_back(num);
}
return res;
}
};
recursion vision:
class Solution {
public:
vector<vector<int> > permute(vector<int> &num) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<vector<int> > res;
if(num.size() == 0)
return res;
vector<int> tmp;
sort(num.begin(),num.end());
map<int,int> hash;
permutation(0,num,res,hash,tmp);
return res;
}
void permutation(int pos, vector<int> &num, vector<vector<int> > &res, map<int,int> &hash, vector<int> &tmp)
{
if(pos == num.size())
{
res.push_back(tmp);
return ;
}
for(int i = 0; i < num.size(); i++)
{
if(hash[num[i]] != 1)
{
tmp.push_back(num[i]);
hash[num[i]] = 1;
permutation(pos + 1, num, res, hash, tmp);
hash[num[i]] = 0;
tmp.pop_back();
}
}
return ;
}
};