对于一个只由0(假)、1(真)、&(逻辑与)、|(逻辑或)和^(异或)五种字符组成的逻辑表达式,再给定一个结果值。现在可以对这个没有括号的表达式任意加合法的括号,返回得到能有多少种加括号的方式,可以达到这个结果。
给定一个字符串表达式exp及它的长度len,同时给定结果值ret,请返回方案数。保证表达式长度小于等于300。为了防止溢出,请返回答案Mod 10007的值。
测试样例:
"1^0|0|1",7,0
返回:2
#"1^0|0|1",7,0
def solution8(test_str, aim, left, right):
if left == right:
if test_str[left] == "1":
if aim == 1:
return 1
else:
return 0
else:
if aim == 1:
return 0
else:
return 1
ret = 0
if aim:
for i in range(l+1,r,2):
if test_str[i] == "&":
ret += solution8(test_str, True, l, i-1) * solution8(test_str, True, i+1, r)
elif test_str[i] == "|":
ret += solution8(test_str, False, l, i-1) * solution8(test_str, True, i+1, r)
ret += solution8(test_str, True, l, i - 1) * solution8(test_str, True, i + 1, r)
ret += solution8(test_str, True, l, i - 1) * solution8(test_str, False, i + 1, r)
elif test_str[i] == "^":
ret += solution8(test_str, False, l, i - 1) * solution8(test_str, True, i + 1, r)
ret += solution8(test_str, True, l, i - 1) * solution8(test_str, False, i + 1, r)
else:
for i in range(l+1,r,2):
if test_str[i] == "|":
ret += solution8(test_str, False, l, i-1) * solution8(test_str, False, i+1, r)
elif test_str[i] == "&":
ret += solution8(test_str, False, l, i-1) * solution8(test_str, True, i+1, r)
ret += solution8(test_str, False, l, i - 1) * solution8(test_str, False, i + 1, r)
ret += solution8(test_str, True, l, i - 1) * solution8(test_str, False, i + 1, r)
elif test_str[i] == "^":
ret += solution8(test_str, True, l, i - 1) * solution8(test_str, True, i + 1, r)
ret += solution8(test_str, False, l, i - 1) * solution8(test_str, False, i + 1, r)
return ret
链接:https://www.nowcoder.com/questionTerminal/ec646f8954e64453bf1a9899a27cfbd6?source=relative 来源:牛客网
如果期望A & B为true,
那么可行解数目 = 表达式A为true的方案数×表达式B为true的方案数;
如果期望A | B为true,
那么可行解数目 = 表达式A为true的方案数×表达式B为false的方案数 + 表达式A为false的方案数×表达式B为true的方案数 +
表达式A为true的方案数×表达式B为true的方案数;
如果期望A ^ B为true,
那么可行解数目 = 表达式A为true的方案数×表达式B为false的方案数 +
表达式A为false的方案数×表达式B为true的方案数;
1737

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



