Given a collection of numbers, return all possible permutations.
For example,
Answer:[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> > res;
res.clear();
if (num.size() == 0)return res;
Permutation(0, num.size(), num, res);
return res;
}
void Permutation(int begin, int n, vector<int> &num, vector<vector<int> > &res){
if(begin == n){
res.push_back(num);
return;
}
for (int j = begin; j < n; ++j) {
swap(num[begin], num[j]);
Permutation(begin + 1,n, num, res);
swap(num[begin], num[j]);
}
return;
}
};
No comments:
Post a Comment