LeetCode 题解工作台
赛车
你的赛车可以从位置 0 开始,并且速度为 +1 ,在一条无限长的数轴上行驶。赛车也可以向负方向行驶。赛车可以按照由加速指令 'A' 和倒车指令 'R' 组成的指令序列自动行驶。 当收到指令 'A' 时,赛车这样行驶: position += speed speed *= 2 当收到指令 'R' 时,…
1
题型
4
代码语言
3
相关题
当前训练重点
困难 · 状态·转移·动态规划
答案摘要
设 表示到达位置 的最短指令序列的长度。答案为 。 对于任意位置 ,都有 $2^{k-1} \leq i \lt 2^k$,并且我们可以有三种方式到达位置 :
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
0 开始,并且速度为 +1 ,在一条无限长的数轴上行驶。赛车也可以向负方向行驶。赛车可以按照由加速指令 'A' 和倒车指令 'R' 组成的指令序列自动行驶。
- 当收到指令
'A'时,赛车这样行驶:position += speedspeed *= 2
- 当收到指令
'R'时,赛车这样行驶:- 如果速度为正数,那么
speed = -1 - 否则
speed = 1
- 如果速度为正数,那么
例如,在执行指令 "AAR" 后,赛车位置变化为 0 --> 1 --> 3 --> 3 ,速度变化为 1 --> 2 --> 4 --> -1 。
给你一个目标位置 target ,返回能到达目标位置的最短指令序列的长度。
示例 1:
输入:target = 3 输出:2 解释: 最短指令序列是 "AA" 。 位置变化 0 --> 1 --> 3 。
示例 2:
输入:target = 6 输出:5 解释: 最短指令序列是 "AAARA" 。 位置变化 0 --> 1 --> 3 --> 7 --> 7 --> 6 。
提示:
1 <= target <= 104
解题思路
方法一:动态规划
设 表示到达位置 的最短指令序列的长度。答案为 。
对于任意位置 ,都有 ,并且我们可以有三种方式到达位置 :
- 如果 等于 ,那么我们可以直接执行 个
A指令到达位置 ,此时 ; - 否则,我们可以先执行 个
A指令到达位置 ,然后执行R指令,剩余距离为 ,此时 ;我们也可以先执行 个A指令到达位置 ,然后执行R指令,接着执行 (其中 ) 个A,再执行R,剩余距离为 ,此时 。求出 的最小值即可。
时间复杂度 ,其中 为 。
class Solution:
def racecar(self, target: int) -> int:
dp = [0] * (target + 1)
for i in range(1, target + 1):
k = i.bit_length()
if i == 2**k - 1:
dp[i] = k
continue
dp[i] = dp[2**k - 1 - i] + k + 1
for j in range(k - 1):
dp[i] = min(dp[i], dp[i - (2 ** (k - 1) - 2**j)] + k - 1 + j + 2)
return dp[target]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Can the candidate identify and optimize the state transitions for minimal steps?
- question_mark
Does the candidate consider the use of dynamic programming or BFS to solve the problem efficiently?
- question_mark
How well does the candidate handle space and time optimization, such as with memoization?
常见陷阱
外企场景- error
Not considering negative speeds or positions when calculating the car’s movements.
- error
Failing to optimize the search space with memoization or state space reduction.
- error
Overcomplicating the solution by not using dynamic programming or BFS to explore the shortest path efficiently.
进阶变体
外企场景- arrow_right_alt
What if the target is very large? Consider the impact of expanding the state space.
- arrow_right_alt
What if the car could change its speed more than once per step? This would introduce a different dynamic in the state transition.
- arrow_right_alt
What if the target position was negative? The solution would need to account for reversing and going in the negative direction.