Permutations II
Code:
class Solution { public: int maxDep; vector<int>buf; vector<vector<int>> res; 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(i!=0&&valid[i-1]&&num[i-1]==num[i]) continue; if(valid[i]){ valid[i]=false; buf.push_back(num[i]); dfs(dep+1,valid,num); valid[i]=true; buf.pop_back(); } } } vector<vector<int>> permuteUnique(vector<int> &num) { buf.clear(); res.clear(); if(num.empty()) return res; sort(num.begin(),num.end()); // sort vector<bool> valid(num.size(),true); maxDep = num.size(); dfs(0,valid, num); return res; } };