1. Title
Given a Boolean expression and a Boolean result desired result, a Boolean expression consists of 0 (false)、1 (true)、& (AND)、 | (OR) 和 ^ (XOR)
symbols.
Implement a function and work out several parenthetical methods that allow the expression to get the result value.
示例 1:
输入: s = "1^0|0|1", result = 0
输出: 2
解释: 两种可能的括号方法是
1^(0|(0|1))
1^((0|0)|1)
示例 2:
输入: s = "0&0&0&1^1|0", result = 1
输出: 10
提示:
运算符的数量不超过 19 个
Source: LeetCode
Link: https://leetcode-cn.com/problems/boolean-evaluation-lcci
Copyright belongs to Deduction Network. Please contact the official authorization for commercial reprint, and please indicate the source for non-commercial reprint.
2. Interval DP problem solving
dp?[i][j]
Interval represents[i,j]
the arithmetic value of?(0 or 1)
the number of programs- Initialize, at each digit
dp?[i][i]=1, if s[i]==?
- Then
len
increase by length and solvedp[i][i+len]
dp[i][i+len]
The solution can be obtained according to the product of the left and right sides of its internal solution- So it is divided into two parts
dp[i,j],dp[j+2][i+len]
, iterates over allj
,j+1
and the operator is - Then, according to the three possibilities of the operator, discuss the result of 0,1, and add up
class Solution {
public:
int countEval(string s, int result) {
if(s=="")
return 0;
int i, j, n = s.size(), len;
vector<vector<int>> dp0(n,vector<int>(n,0));
vector<vector<int>> dp1(n,vector<int>(n,0));
//dp?[i][j] 表示 区间[i,j]内运算值为 ? 的方案数
for(i = 0; i < n; i+=2)
{
if(s[i]=='1')
dp1[i][i] = 1;
else
dp0[i][i] = 1;
}
for(len = 2; len <= n-1; len += 2)
{ //按长度递增
for(i = 0; i < n-len; i += 2)
{ //左端点i
for(j = i; j <= i+len-2; j+=2)
{ //中间端点j
if(s[j+1]=='&')
{
dp1[i][i+len] += dp1[i][j]*dp1[j+2][i+len];
dp0[i][i+len] += dp0[i][j]*dp0[j+2][i+len]+dp1[i][j]*dp0[j+2][i+len]+dp0[i][j]*dp1[j+2][i+len];
}
else if(s[j+1]=='|')
{
dp1[i][i+len] += dp1[i][j]*dp1[j+2][i+len]+dp1[i][j]*dp0[j+2][i+len]+dp0[i][j]*dp1[j+2][i+len];
dp0[i][i+len] += dp0[i][j]*dp0[j+2][i+len];
}
else//^
{
dp1[i][i+len] += dp1[i][j]*dp0[j+2][i+len]+dp0[i][j]*dp1[j+2][i+len];
dp0[i][i+len] += dp0[i][j]*dp0[j+2][i+len]+dp1[i][j]*dp1[j+2][i+len];
}
}
}
}
if(result)
return dp1[0][n-1];
return dp0[0][n-1];
}
};
8 ms 7 MB