Approach
Sorting and greedy selection
For Permuteunique, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 42 lines of C++ from the credited upstream file permuteUnique.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 2 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4class Solution {5 public:6 vector<vector<int> > permuteUnique(vector<int>& num) {7 sort(num.begin(), num.end());8 unordered_map<int, int> count_map;9 for(auto e : num) {10 if (count_map.find(e) != count_map.end())11 count_map[e]++;12 else13 count_map[e] = 1;14 }15 16 vector<vector<int> > ans;17 vector<int> path;18 n = num.size();19 permute(count_map, path, ans);20 21 return ans;22 }23 24 private:25 size_t n;26 void permute(unordered_map<int, int> &count_map, vector<int> &path, vector<vector<int> > &ans) {27 if (n == path.size()) {28 ans.push_back(path);29 }30 31 for (auto i = count_map.begin(); i != count_map.end(); ++i) {32 if (i->second) {33 path.push_back(i->first);34 i->second--;35 permute(count_map, path, ans);36 path.pop_back();37 i->second++;38 }39 }40 }41};42