-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path03_unique_permutations_using_set.cpp
73 lines (58 loc) · 1.31 KB
/
03_unique_permutations_using_set.cpp
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
Topic - Unique Permutations (using set STL)
Given a string s, task is to find all unique permutation of the string s.
Input : aba
Output : aab, aba, baa
Explaination: all permutaions: aab, aba, baa, baa, aba, aab,
unique : aab, aba, baa,
*/
#include <iostream>
#include <set>
#include <string>
using namespace std;
// function find all permutations
void uniquePermute(char *inp, int idx, set<string> &s)
{
// Base Case
if(inp[idx] == '\0')
{
// cout << inp << ", ";
string str = inp;
s.insert(str);
return;
}
// Recursive Case
for(int j=idx; inp[j] != '\0'; j++)
{
swap(inp[idx], inp[j]);
uniquePermute(inp, idx+1, s);
// backtracing: to restore the original array
swap(inp[idx], inp[j]);
}
}
// function to drive code
int main()
{
char ch[100];
cout << "Enter your string: ";
cin >> ch;
set<string> s;
uniquePermute(ch, 0, s);
// loop over the set s
cout << "Unique Permutations: ";
for(auto str:s)
{
cout << str << ", ";
}
cout << endl;
return 0;
}
/*
OUTPUT:
Case 1:
Enter your string : aba
Unique Permutations : aab, aba, baa,
Case 2:
Enter your string : 121
Unique Permutations : 112, 121, 211,
*/