LeetCode面试题 08.14. Boolean Evaluation LCCI——区间dp

一、题目

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};
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值