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<vector<int> > ivecArray;
if (num.size() == 0)
return ivecArray;
recursive(ivecArray, num, 0);
return ivecArray;
}
void recursive(vector<vector<int> > &ivecArray, vector<int> &num, int start) {
int n = num.size();
if (start == n) {
ivecArray.push_back(num);
return;
}
for (int i = start; i < n; i++) {
swap(num[i], num[start]);
recursive(ivecArray, num, start + 1);
swap(num[i], num[start]);
}
}
};
使用STL库函数
class Solution {
public:
vector<vector<int> > permute(vector<int> &num) {
vector<vector<int> > ivecArray;
if (num.size() == 0)
return ivecArray;
sort(num.begin(), num.end());
ivecArray.push_back(num);
while (next_permutation(num.begin(), num.end())) {
ivecArray.push_back(num);
}
return ivecArray;
}
};