[Geeks for Geeks] All Unique Permutations of an array

All Unique Permutations of an array

Given an array arr[] of length n. Find all possible unique permutations of the array.

  • Time : O(n!)
  • Space : O(n!)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
vector<vector<int>> res;
void helper(vector<int>& builder, unordered_map<int, int>& freq, int& n) {
if(builder.size() == n) res.push_back(builder);
else {
for(auto p : freq) {
if(p.second == 0) continue;
freq[p.first] -= 1;
builder.push_back(p.first);
helper(builder, freq, n);
builder.pop_back();
freq[p.first] += 1;
}
}
}
public:
vector<vector<int>> uniquePerms(vector<int> arr ,int n) {
res.clear();
unordered_map<int, int> freq;

for(auto& a : arr) freq[a]++;

helper(vector<int>() = {}, freq, n);

sort(begin(res), end(res));
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/27/PS/GeeksforGeeks/all-unique-permutations-of-an-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.