题目:
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:
bool* nums;
vector<int> tmp;
vector<vector<int> > v;
int len;
vector<vector<int> > permute(vector<int> &num) {
len = num.size();
nums = new bool[len];
for(int k=0;k<len;k++)
{
nums[k]=true;
}
generatePermute(num);
return v;
}
void generatePermute(vector<int> &num)
{
if(tmp.size() == len)
{
v.push_back(tmp);
}
else
{
for(int i=0;i<len;i++)
{
if(nums[i])
{
nums[i]=false;
tmp.push_back(num[i]);
generatePermute(num);
nums[i]=true;
tmp.pop_back();
}
}
}
}
};