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:
void perTravel(vector<vector<int> > &result, vector<int> &num, int n){
if(n == num.size()){
result.push_back(num);
} else {
for(int i=n; i<num.size(); i++){
std::swap(num[i], num[n]);
perTravel(result, num, n+1);
std::swap(num[i], num[n]);
}
}
}
vector<vector<int> > permute(vector<int> &num) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
vector<vector<int> > result;
perTravel(result, num, 0);
return result;
}
};