forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathValid Permutations for DI Sequence.cpp
72 lines (72 loc) · 2.17 KB
/
Valid Permutations for DI Sequence.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
class Solution {
public:
int numPermsDISequence(string s) {
int n=s.length();
queue<pair<string,unordered_set<int>>> q;
unordered_set<int> v;
string str="";
for(int i=0;i<=n;++i)
{
str="";
v.clear();
str+=(i+'0');
v.insert(i);
q.push({str,v});
}
int i=0;
unordered_set<string> visall;
while(!q.empty())
{
int sz=q.size();
if(i==n)
{
return q.size();
}
while(sz--)
{
auto temp=q.front();
q.pop();
if(visall.find(temp.first)!=visall.end())
{
continue;
}
if(s[i]=='D')
{
for(int j=temp.first.back()-'0'-1;j>=0;--j)
{
if(temp.second.find(j)==temp.second.end())
{
temp.first+=(j+'0');
temp.second.insert(j);
if(visall.find(temp.first)==visall.end())
{
q.push({temp.first,temp.second});
}
temp.second.erase(j);
temp.first.pop_back();
}
}
}
else
{
for(int j=temp.first.back()-'0'+1;j<=n;++j)
{
if(temp.second.find(j)==temp.second.end())
{
temp.first+=(j+'0');
temp.second.insert(j);
if(visall.find(temp.first)==visall.end())
{
q.push({temp.first,temp.second});
}
temp.second.erase(j);
temp.first.pop_back();
}
}
}
}
i++;
}
return 0;
}
};