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 sub(vector<vector<int> > & ret,vector<int>& num,int index){ if(index==num.size()){ ret.push_back(num); return ; } int temp; for(int i=index;i<num.size();i++){ temp=num[i]; num[i]=num[index]; num[index]=temp; sub(ret,num,index+1); temp=num[i]; num[i]=num[index]; num[index]=temp; } } vector<vector<int> > permute(vector<int> &num) { // Note: The Solution object is instantiated only once and is reused by each test case. vector<vector<int> >ret; sub(ret,num,0); return ret; } };