【发布时间】:2011-10-05 19:40:49
【问题描述】:
给定一个包含符号 {true, false, and, or, xor} 的布尔表达式,计算为表达式加上括号以使其计算结果为 true 的次数。
例如,只有 1 种方法可以将“真假异或真”括起来,使其计算结果为真。
这是我的算法
we can calculate the total number of parenthesization of a string
Definition:
N - the total number of
True - the number of parenthesizations that evaluates to true
False - the number of parenthesizations that evaluates to false
True + False = N
Left_True - the number of parenthesization in the left part that evaluates to True
same to Left_False, Right_True, Right_False
we iterate the input string from left to right and deal with each operator as follows:
if it is "and", the number of parenthesization leads to true is
Left_True * Right_True;
if it is "xor", the number of parenthesization leads to true
Left_True * Right_False + Left_False * Right_True
if it is 'or', the number is
N - Left_False * Right_False
Here is my psuedocode
n = number of operator within the String
int[n][n] M; // save number of ways evaluate to true
for l = 2 to n
for i = 1 to n-l+1
do j = i+l-1
// here we have different string varying from 2 to n starting from i and ending at j
for k = i to j-1
// (i,k-1) is left part
// (k+1, j) is right part
switch(k){
case 'and': // calculate, update array m
case 'or': // same
case 'xor':
}
we save all the solutions to subproblems and read them when we meet them again. thus save time.
我们能有更好的解决方案吗?
【问题讨论】:
-
“我们能有更好的解决方案”是什么意思?假设您要一个:请定义“更好”。您是否正在寻找一种更快的解决方案,一种使用更少的代码,更少的内存使用......此外,您可能想进一步澄清您的伪代码,我曾经很难弄清楚它应该如何工作(它可能如果您写下开关内部发生的事情,请提供帮助
-
我正在寻找更快的解决方案和更少的代码实现。比如计算括号的方式很繁琐,括号导致真假
-
我很困惑——
(true and false) xor true和true and (false xor true)都评估为真。 -
@ben 如果操作顺序是从左到右,那么“真假异或真”也是一种解决方案
-
我也很困惑:
if it is 'or', the number is N - Left_False * Right_False。我有一种感觉,除了 N 之外,还有更多的括号
标签: algorithm implementation dynamic-programming