LeetCode 题解工作台
向表达式添加括号后的最小结果
给你一个下标从 0 开始的字符串 expression ,格式为 " + " ,其中 和 表示正整数。 请你向 expression 中添加一对括号,使得在添加之后, expression 仍然是一个有效的数学表达式,并且计算后可以得到 最小 可能值。左括号 必须 添加在 '+' 的左侧,而右括号必…
2
题型
3
代码语言
3
相关题
当前训练重点
中等 · string·结合·enumeration
答案摘要
class Solution: def minimizeResult(self, expression: str) -> str:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 string·结合·enumeration 题型思路
题目描述
给你一个下标从 0 开始的字符串 expression ,格式为 "<num1>+<num2>" ,其中 <num1> 和 <num2> 表示正整数。
请你向 expression 中添加一对括号,使得在添加之后, expression 仍然是一个有效的数学表达式,并且计算后可以得到 最小 可能值。左括号 必须 添加在 '+' 的左侧,而右括号必须添加在 '+' 的右侧。
返回添加一对括号后形成的表达式 expression ,且满足 expression 计算得到 最小 可能值。如果存在多个答案都能产生相同结果,返回任意一个答案。
生成的输入满足:expression 的原始值和添加满足要求的任一对括号之后 expression 的值,都符合 32-bit 带符号整数范围。
示例 1:
输入:expression = "247+38"
输出:"2(47+38)"
解释:表达式计算得到 2 * (47 + 38) = 2 * 85 = 170 。
注意 "2(4)7+38" 不是有效的结果,因为右括号必须添加在 '+' 的右侧。
可以证明 170 是最小可能值。
示例 2:
输入:expression = "12+34" 输出:"1(2+3)4" 解释:表达式计算得到 1 * (2 + 3) * 4 = 1 * 5 * 4 = 20 。
示例 3:
输入:expression = "999+999" 输出:"(999+999)" 解释:表达式计算得到 999 + 999 = 1998 。
提示:
3 <= expression.length <= 10expression仅由数字'1'到'9'和'+'组成expression由数字开始和结束expression恰好仅含有一个'+'.expression的原始值和添加满足要求的任一对括号之后expression的值,都符合 32-bit 带符号整数范围
解题思路
方法一:枚举左右括号的插入位置
class Solution:
def minimizeResult(self, expression: str) -> str:
l, r = expression.split("+")
m, n = len(l), len(r)
mi = inf
ans = None
for i in range(m):
for j in range(n):
c = int(l[i:]) + int(r[: j + 1])
a = 1 if i == 0 else int(l[:i])
b = 1 if j == n - 1 else int(r[j + 1 :])
if (t := a * b * c) < mi:
mi = t
ans = f"{l[:i]}({l[i:]}+{r[: j + 1]}){r[j + 1:]}"
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
They point out that the expression length is tiny, which is a strong signal to enumerate all parenthesis placements.
- question_mark
They ask how multiplication appears after adding parentheses, which hints that outside digits become prefix and suffix multipliers.
- question_mark
They care more about correctness than clever pruning, which usually means brute force is the intended pattern for this String plus Enumeration problem.
常见陷阱
外企场景- error
Forgetting that an empty prefix or empty suffix should contribute 1, not 0, which breaks cases like (999+999).
- error
Placing parentheses in invalid positions, such as ending before the plus or starting after it, which violates the problem constraints.
- error
Using a greedy idea like minimizing the inside sum alone, even though a slightly larger sum can still win if it avoids a large outer multiplier.
进阶变体
外企场景- arrow_right_alt
Return the minimum numeric value instead of the final parenthesized string.
- arrow_right_alt
Allow multiple plus signs, which turns simple enumeration into a more complex expression optimization problem.
- arrow_right_alt
Ask for the maximum result instead of the minimum, which keeps the same enumeration structure but flips the comparison.