-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPermutationsII.cpp
More file actions
41 lines (37 loc) · 1.06 KB
/
PermutationsII.cpp
File metadata and controls
41 lines (37 loc) · 1.06 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <bits/stdc++.h>
using namespace std;
void solve(vector<vector<int>> &pmt, string &str, vector<int> &nums, int i, unordered_set<string> &seen) {
if (i == str.size()) {
if (!seen.count(str)) {
seen.insert(str);
pmt.push_back(nums);
return;
}
for (int j = i; j < nums.size(); j++) {
swap(nums[i], nums[j]);
swap(str[i], str[j]);
solve(pmt, str, nums, i + 1, seen);
swap(nums[i], nums[j]);
swap(str[i], str[j]);
}
}
}
vector<vector<int>> permuteUnique(vector<int> &nums) {
vector<vector<int>> pmt;
string str = "";
for (int i : nums) str.append(to_string(i));
unordered_set<string> seen;
solve(pmt, str, nums, 0, seen);
return pmt;
}
int main() {
int n;
cin >> n;
vector<int> nums(n);
for (int i = 0; i < n; i++) cin >> nums[i];
auto out = permuteUnique(nums);
for (auto x : out) {
for (auto y : x) cout << y << " ";
cout << endl;
}
}