-
Notifications
You must be signed in to change notification settings - Fork 0
/
40. Evaluate Expression To True Boolean Parenthesization Memoized
145 lines (94 loc) · 2.81 KB
/
40. Evaluate Expression To True Boolean Parenthesization Memoized
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
40). Evaluate Expression To True Boolean Parenthesization Memoized
Video Link : https://youtu.be/bzXM1Zond9U
GFG Practice Link : https://practice.geeksforgeeks.org/problems/boolean-parenthesization5610/1
------->>>>>>>>>>>------------>>>>>>>>>>>>________CODE________<<<<<<<<<<<<------------<<<<<<<<<<<<<<<<<<<<<<<<<<<
// User function Template for C++
class Solution{
public:
unordered_map<string,int> m;
int solve(int i,int j,string s,bool isTrue)
{
// base conditions
if(i>j)
{
return 0;
}
if(i==j)
{
if(isTrue==true) // if we needed true output
{
if(s[i]=='T') // if the ith character is 'T'
{
return 1;
// can use true or false also , in C++ true=1 & false = 0
}
else
// i.e isTrue=False , we needed false as output
{
return 0;
}
}
else
{
return s[i]=='F' ? 1: 0;
}
}
// to precheck the value in our in our map
string temp="";
temp=to_string(i);
temp+=" ";
temp+= to_string(j);
temp+=" ";
temp+= to_string(isTrue);
if(m.find(temp)!=m.end())
{
return m[temp];
}
int ans=0;
for(int k=i+1;k<=j-1;k=k+2)
{
int leftTrue=solve(i,k-1,s,true);
int leftFalse=solve(i,k-1,s,false);
int rightTrue=solve(k+1,j,s,true);
int rightFalse=solve(k+1,j,s,false);
if(s[k]=='&')
{
if(isTrue==true)
{
ans+=leftTrue*rightTrue;
}
else
{
ans+=leftTrue*rightFalse +leftFalse*rightTrue+ leftFalse*rightFalse;
}
}
if(s[k]=='|')
{
if(isTrue==true)
{
ans+=leftTrue*rightTrue + leftFalse * rightTrue + leftTrue* rightFalse;
}
else {
ans+=leftFalse * rightFalse;
}
}
if(s[k]=='^')
{
if(isTrue==true)
{
ans+=leftTrue*rightFalse + leftFalse* rightTrue;
}
else
{
ans+=leftTrue* rightTrue + leftFalse*rightFalse;
}
}
}
return m[temp]=ans%1003;
}
int countWays(int n, string s){
int i=0,j=n-1;
int ans= solve(i,j,s,true);
return ans %1003;
}
};