题目描述:
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 swap(int * a,int * b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void permuteRecursive(vector<int> & num,int begin,vector<vector<int>> & result)
{
if(begin == num.size())
{
result.push_back(num);
return;
}
for(int i = begin;i < num.size();i++)
{
swap(&num[begin],&num[i]);
permuteRecursive(num,begin+1,result);
swap(&num[begin],&num[i]);
}
}
vector<vector<int>> permute(vector<int> & nums)
{
vector<vector<int>> result;
permuteRecursive(nums,0,result);
return result;
}
};