Permutations
Code:
class Solution { public: int maxDep; vector<int> buf; // pack numbers into an array vector<vector<int>> res; // pack arrays into an result void dfs(int dep, vector<bool> &valid, vector<int> &num){ if(dep==maxDep){ res.push_back(buf); return; } for(int i=0; i<maxDep;i++) if(valid[i]){ valid[i]=false; buf.push_back(num[i]); dfs(dep+1,valid, num); buf.pop_back(); valid[i]=true; } } vector<vector<int> > permute(vector<int> &num) { res.clear(); buf.clear(); if(num.empty()) return res; vector<bool> valid(num.size(),true); maxDep = num.size(); dfs(0,valid, num); return res; } };