LeetCode 题解工作台
表示数字的最少运算符
给定一个正整数 x ,我们将会写出一个形如 x (op1) x (op2) x (op3) x ... 的表达式,其中每个运算符 op1 , op2 ,… 可以是加、减、乘、除( + , - , * ,或是 / )之一。例如,对于 x = 3 ,我们可以写出表达式 3 * 3 / 3 + 3 - 3…
3
题型
5
代码语言
3
相关题
当前训练重点
困难 · 状态·转移·动态规划
答案摘要
我们定义一个函数 ,表示用 凑成数字 所需要的最少运算符数量。那么答案就是 。 函数 的执行逻辑如下:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给定一个正整数 x,我们将会写出一个形如 x (op1) x (op2) x (op3) x ... 的表达式,其中每个运算符 op1,op2,… 可以是加、减、乘、除(+,-,*,或是 /)之一。例如,对于 x = 3,我们可以写出表达式 3 * 3 / 3 + 3 - 3,该式的值为 3 。
在写这样的表达式时,我们需要遵守下面的惯例:
- 除运算符(
/)返回有理数。 - 任何地方都没有括号。
- 我们使用通常的操作顺序:乘法和除法发生在加法和减法之前。
- 不允许使用一元否定运算符(
-)。例如,“x - x” 是一个有效的表达式,因为它只使用减法,但是 “-x + x” 不是,因为它使用了否定运算符。
我们希望编写一个能使表达式等于给定的目标值 target 且运算符最少的表达式。返回所用运算符的最少数量。
示例 1:
输入:x = 3, target = 19 输出:5 解释:3 * 3 + 3 * 3 + 3 / 3 。表达式包含 5 个运算符。
示例 2:
输入:x = 5, target = 501 输出:8 解释:5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5 。表达式包含 8 个运算符。
示例 3:
输入:x = 100, target = 100000000 输出:3 解释:100 * 100 * 100 * 100 。表达式包含 3 个运算符。
提示:
2 <= x <= 1001 <= target <= 2 * 108
解题思路
方法一:记忆化搜索
我们定义一个函数 ,表示用 凑成数字 所需要的最少运算符数量。那么答案就是 。
函数 的执行逻辑如下:
如果 ,那么此时可以用 个 相加来得到 ,运算符数量为 ;也可以用 减去 个 来得到 ,运算符数量为 。取两者的最小值。
否则,我们从 开始枚举 ,找到第一个 的 :
- 如果此时 ,那么只能先得到 ,然后再递归计算 ,此时运算符数量为 ;
- 如果此时 ,那么可以按照上面的方式得到 ,此时运算符数量为 ;也可以先得到 ,再递归计算 ,此时运算符数量为 。取两者的最小值。
为了避免重复计算,我们使用记忆化搜索的方式实现 函数。
时间复杂度 ,空间复杂度 。
class Solution:
def leastOpsExpressTarget(self, x: int, target: int) -> int:
@cache
def dfs(v: int) -> int:
if x >= v:
return min(v * 2 - 1, 2 * (x - v))
k = 2
while x**k < v:
k += 1
if x**k - v < v:
return min(k + dfs(x**k - v), k - 1 + dfs(v - x ** (k - 1)))
return k - 1 + dfs(v - x ** (k - 1))
return dfs(target)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | and space complexity depend on the range of powers of x considered and the memoization of sub-targets. Recursive state transitions reduce redundant calculations, but worst-case depth relates to log_x(target). |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Ask how to minimize operators when combining powers of x.
- question_mark
Probe understanding of memoization in recursive state transitions.
- question_mark
Check if candidates handle both quotient and remainder optimally.
常见陷阱
外企场景- error
Failing to account for both addition and subtraction when splitting target.
- error
Recomputing operator counts without memoization, causing timeouts.
- error
Incorrectly counting operators for powers of x or ignoring division edge cases.
进阶变体
外企场景- arrow_right_alt
Restrict expressions to only addition and multiplication and find minimal operators.
- arrow_right_alt
Allow negative x and explore impact on operator minimization.
- arrow_right_alt
Find expressions minimizing total operands instead of operators.