一、题目
Given a boolean expression consisting of the symbols 0 (false), 1 (true), & (AND), | (OR), and ^ (XOR), and a desired boolean result value result, implement a function to count the number of ways of parenthesizing the expression such that it evaluates to result.
Example 1:
Input: s = “1^0|0|1”, result = 0
Output: 2
Explanation: Two possible parenthesizing ways are:
1^(0|(0|1))
1^((0|0)|1)
Example 2:
Input: s = “0&0&0&1^1|0”, result = 1
Output: 10
Note:
There are no more than 19 operators in s.
二、题解
class Solution {
public:
int countEval(string s, int result) {
int n = s.size();
vector<vector<vector<int>>> dp(n,vector<vector<int>>(n,vector<int>(3,0)));
vector<int> ft = func(s, 0, n - 1, dp);
return ft[result];
}
vector<int> func(string s,int l,int r,vector<vector<vector<int>>>& dp){
if(dp[l][r][2] != 0) return dp[l][r];
int f = 0,t = 0;
if (l == r) {
f = s[l] == '0' ? 1 : 0;
t = s[l] == '1' ? 1 : 0;
} else {
vector<int> tmp;
for (int k = l + 1, a, b, c, d; k < r; k += 2) {
tmp = func(s, l, k - 1, dp);
a = tmp[0];
b = tmp[1];
tmp = func(s, k + 1, r, dp);
c = tmp[0];
d = tmp[1];
if (s[k] == '&') {
f += a * c + a * d + b * c;
t += b * d;
} else if (s[k] == '|') {
f += a * c;
t += a * d + b * c + b * d;
} else {
f += a * c + b * d;
t += a * d + b * c;
}
}
}
dp[l][r][0] = f;
dp[l][r][1] = t;
dp[l][r][2] = 1;
return {f,t};
}
};
1436

被折叠的 条评论
为什么被折叠?



