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 DFS(vector<vector<int> > &res,vector<int> &ans,vector<bool> flag,vector<int> &num) { if(ans.size()==num.size()) { res.push_back(ans); return; } for(int i=0;i<num.size();i++) { if(!flag[i]) { ans.push_back(num[i]); flag[i]=true; DFS(res,ans,flag,num); flag[i]=false; ans.pop_back(); } } } vector<vector<int> > permute(vector<int> &num) { vector<vector<int> > res; vector<int> ans; vector<bool> flag(num.size(),false); DFS(res,ans,flag,num); return res; } };