Skip to content

Commit 4634d0e

Browse files
author
lifeiyang
committed
2022-11-20-21:33:57
1 parent ee8fe23 commit 4634d0e

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
from typing import List
2+
3+
4+
# leetcode submit region begin(Prohibit modification and deletion)
5+
class Solution:
6+
def diffWaysToCompute(self, expression: str) -> List[int]:
7+
res = []
8+
for idx, c in enumerate(expression):
9+
if c in ["*", "-", "+"]:
10+
left_list = self.diffWaysToCompute(expression[:idx])
11+
right_list = self.diffWaysToCompute(expression[idx + 1:])
12+
for left in left_list:
13+
for right in right_list:
14+
if c == "*":
15+
res.append(left * right)
16+
if c == "-":
17+
res.append(left - right)
18+
if c == "+":
19+
res.append(left + right)
20+
21+
if len(res) == 0:
22+
# 说明其中没有 * - + 等符号,纯数字
23+
res.append(int(expression))
24+
return res
25+
26+
27+
# leetcode submit region end(Prohibit modification and deletion)
28+
29+
if __name__ == "__main__":
30+
solution = Solution()
31+
print(solution.diffWaysToCompute("2*3-4*5"))
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<p>给你一个由数字和运算符组成的字符串&nbsp;<code>expression</code> ,按不同优先级组合数字和运算符,计算并返回所有可能组合的结果。你可以 <strong>按任意顺序</strong> 返回答案。</p>
2+
3+
<p>生成的测试用例满足其对应输出值符合 32 位整数范围,不同结果的数量不超过 <code>10<sup>4</sup></code> 。</p>
4+
5+
<p>&nbsp;</p>
6+
7+
<p><strong>示例 1:</strong></p>
8+
9+
<pre>
10+
<strong>输入:</strong>expression = "2-1-1"
11+
<strong>输出:</strong>[0,2]
12+
<strong>解释:</strong>
13+
((2-1)-1) = 0
14+
(2-(1-1)) = 2
15+
</pre>
16+
17+
<p><strong>示例 2:</strong></p>
18+
19+
<pre>
20+
<strong>输入:</strong>expression = "2*3-4*5"
21+
<strong>输出:</strong>[-34,-14,-10,-10,10]
22+
<strong>解释:</strong>
23+
(2*(3-(4*5))) = -34
24+
((2*3)-(4*5)) = -14
25+
((2*(3-4))*5) = -10
26+
(2*((3-4)*5)) = -10
27+
(((2*3)-4)*5) = 10
28+
</pre>
29+
30+
<p>&nbsp;</p>
31+
32+
<p><strong>提示:</strong></p>
33+
34+
<ul>
35+
<li><code>1 &lt;= expression.length &lt;= 20</code></li>
36+
<li><code>expression</code> 由数字和算符 <code>'+'</code>、<code>'-'</code> 和 <code>'*'</code> 组成。</li>
37+
<li>输入表达式中的所有整数值在范围 <code>[0, 99]</code>&nbsp;</li>
38+
</ul>
39+
40+
<div><div>Related Topics</div><div><li>递归</li><li>记忆化搜索</li><li>数学</li><li>字符串</li><li>动态规划</li></div></div><br><div><li>👍 767</li><li>👎 0</li></div>

0 commit comments

Comments
 (0)