-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path055_Print Permutations - String.cpp
73 lines (54 loc) · 1.15 KB
/
055_Print Permutations - String.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
// TC -> O(n * N!)
// SC -> O(n)
#include <bits/stdc++.h>
void helper(vector<int> freq, int n,string ds, string &s, vector<string>& ans )
{
if(ds.size() == n)
{
ans.push_back(ds);
return;
}
for(int i = 0; i < n; ++i)
{
if(freq[i] == 0)
{
ds.push_back(s[i]);
freq[i] = 1;
helper(freq, n, ds, s, ans);
freq[i] = 0;
ds.pop_back();
}
}
}
vector<string> findPermutations(string &s) {
// Write your code here.
int n = s.size();
vector<int> freq(n,0);
string ds;
vector<string> ans;
helper(freq,n, ds, s, ans);
return ans;
}
// TC -> O(n * N!)
// SC -> O(1)
#include <bits/stdc++.h>
void helper(int idx, int n, string& s, vector<string>& ans)
{
if (idx == n) {
ans.push_back(s);
return;
}
for(int i = idx; i < n; ++i)
{
swap(s[i], s[idx]);
helper(idx+1, n, s, ans);
swap(s[i], s[idx]);
}
}
vector<string> findPermutations(string &s) {
// Write your code here.
int n = s.size();
vector<string> ans;
helper(0, n, s, ans);
return ans;
}