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]
.
思路:交换思想
1 2 3 -> 1 2 3(1<->1) 2 1 3(1<->2) 3 2 1(1<->3) //第0位即数字1 和所有位交换
第1位 和[1,num.size()-1]位交换,直至第num.size()-1位
class Solution {
public:
vector<vector<int>> res;
void swap(int *a,int *b)
{
int temp=*a;
*a=*b;
*b=temp;
}
void function(vector<int>&num,int i)
{
if(i==num.size()-1)
{
res.push_back(num);
}
else{
for(int j=i;j<num.size();j++)
{
swap(&num[i],&num[j]);
function(num,i+1);
swap(&num[i],&num[j]);
}
}
}
vector<vector<int>> permute(vector<int>&num)
{
if(num.size()>0)
function(num,0);
return res;
}
};