[InterviewBit] All Unique Permutations

All Unique Permutations

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void helper(vector<vector<int>>& res, unordered_map<int,int>& freq, int p, int n, vector<int>& now) {
if(p == n) res.push_back(now);
else {
for(auto& [k,v] : freq) {
if(!v) continue;
v -= 1;
now.push_back(k);
helper(res,freq,p+1,n,now);
now.pop_back();
v += 1;
}
}
}

vector<vector<int>> Solution::permute(vector<int> &A) {
unordered_map<int, int> freq;
for(auto& a : A) freq[a]++;
vector<vector<int>> res;
helper(res,freq,0,A.size(), vector<int>() = {});
return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/21/PS/interviewbit/all-unique-permutations/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.