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]
.
解题思想::DFS,找出一个递归函数,index从1,3
后面选不同的数字交换,
index =1 时 后面是,2 ,3, 有 1,2,3, 1,3,2学会交换swap[i],swap[]
index=2时,
到index=3, 层层遍历,达到叶子节点。。 跟树还很逼近!
class Solution {
public:
void internalPerate(vector<int>& nums,int index,vector<int>& solution,vector<vector<int>> &result)
{
int N=nums.size();
if(index==N)
{
result.push_back(solution);
return;
}
for(int i=index;i<N;i++)//small problem.....
{
swap(nums[index],nums[i]); //around the
solution.push_back(nums[index]);
internalPerate(nums,index+1,solution,result);
solution.pop_back();
swap(nums[index],nums[i]);
}
}
vector<vector<int>> permute(vector<int>& nums)
{
vector<vector<int>> result;
if (nums.size()==0)
{
return result;
}
vector<int> solution;
internalPerate(nums,0,solution,result);
return result;
}
};