Problem
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]
.Code
void permute_r(vector<int> num,vector<int> &result,int l,int n,int pos, vector<vector<int> > &res){ if(pos == n){ res.push_back(vector<int>(result.begin(),result.begin() + pos)); return; } for(int i = l;i < n;++i){ swap(num[l],num[i]); result[pos] = num[l]; permute_r(num,result,l + 1,n,pos + 1,res); } } vector<vector<int> > permute(vector<int> &num) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. vector<vector<int> > res; int n = num.size(); vector<int> result(n); permute_r(num,result,0,n,0,res); return res; }
No comments:
Post a Comment