Problem Description:
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 permutations(vector
num,int begin,vector
&permutation,vector
> &res) { if(begin==num.size()) { res.push_back(permutation); return; } for(vector
::size_type index=begin;index!=num.size();++index) { swap(num[begin],num[index]); permutation.push_back(num[begin]); permutations(num,begin+1,permutation,res); permutation.pop_back(); swap(num[begin],num[index]); } } vector
> permute(vector
&num) { vector
> res; if(num.empty()) return res; vector
permutation; permutations(num,0,permutation,res); return res; } };