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:
<span style="font-size:14px;">class Solution {
public:
void helper(vector<vector<int> > &results, vector<int> &num, const int &length, int index) {
if (index == length) {
results.push_back(num);
return;
}
helper(results, num, length, index+1);
for (int i = index+1; i < length; ++i) {
swap(num[index], num[i]);
helper(results, num, length, index+1);
swap(num[index], num[i]);
}
}
vector<vector<int> > permute(vector<int> &num) {
const int length = num.size();
vector<vector<int> > results;
if (length == 0) return results;
if (length == 1) {
results.push_back(num);
return results;
}
sort(num.begin(), num.end());
helper(results, num, length, 0);
return results;
}
};</span>