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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<vector<int> > result,temp;
vector<int> v;
int len = num.size();
if (len == 0) return result;
if (len == 1)
{
result.push_back(num);
return result;
}
v.push_back(num[0]);
result.push_back(v);
for (int i = 1; i < len; ++i)
{
// the outer loop is use to deal with the new comming number
// we assume num[0] is exist and start from num[1]
for (int j = 0; j < result.size(); ++j)
{
// we pick every vector from result and exchange num[i]
// with every number in vector v than we push back v to
// temp vector
v = result[j];
int tempLen = v.size();
v.push_back(num[i]);
temp.push_back(v);
for (int k = 0; k < tempLen; ++k)
{
// exchage number first,than push back,than recover
int elem = v[k];
v[k] = v[tempLen];
v[tempLen] = elem;
temp.push_back(v);
v[tempLen] = v[k];
v[k] = elem;
}
}
result = temp;
temp.clear();
}
return result;
}
};