-
Notifications
You must be signed in to change notification settings - Fork 0
/
39 Evaluate Expression to True Boolean Parenthesization Recursive
134 lines (88 loc) · 2.69 KB
/
39 Evaluate Expression to True Boolean Parenthesization Recursive
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
39 ). Evaluate Expression to True Boolean Parenthesization Recursive
Video Link : https://youtu.be/pGVguAcWX4g
GFG Practice Link : https://practice.geeksforgeeks.org/problems/boolean-parenthesization5610/1
//Recursive solution
------->>>>>>>>>>>------------>>>>>>>>>>>>________CODE________<<<<<<<<<<<<------------<<<<<<<<<<<<<<<<<<<<<<<<<<<
// User function Template for C++
class Solution{
public:
int solve(int i,int j,int n,string s,bool isTrue)
{
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
{
if(s[i]=='F')
{
// return true;
return 1;
}
else
{
// return false ;
return 0;
}
}
}
int ans=0;
for(int k=i+1;k<=j-1;k=k+2)
{
int leftTrue=solve(i,k-1,n,s,true);
int leftFalse=solve(i,k-1,n,s,false);
int rightTrue=solve(k+1,j,n,s,true);
int rightFalse=solve(k+1,j,n,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 ans;
}
int countWays(int n, string s){
// code here
int i=0,j=n-1;
int ans= solve(i,j,n,s,true);
return ans;
}
};