LeetCode 题解工作台
戳气球
有 n 个气球,编号为 0 到 n - 1 ,每个气球上都标有一个数字,这些数字存在数组 nums 中。 现在要求你戳破所有的气球。戳破第 i 个气球,你可以获得 nums[i - 1] * nums[i] * nums[i + 1] 枚硬币。 这里的 i - 1 和 i + 1 代表和 i 相邻的…
2
题型
6
代码语言
3
相关题
当前训练重点
困难 · 状态·转移·动态规划
答案摘要
我们记数组 的长度为 。根据题目描述,我们可以在数组 的左右两端各添加一个 ,记为 。 然后,我们定义 表示戳破区间 $[i, j]$ 内的所有气球能得到的最多硬币数,那么答案即为 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
有 n 个气球,编号为0 到 n - 1,每个气球上都标有一个数字,这些数字存在数组 nums 中。
现在要求你戳破所有的气球。戳破第 i 个气球,你可以获得 nums[i - 1] * nums[i] * nums[i + 1] 枚硬币。 这里的 i - 1 和 i + 1 代表和 i 相邻的两个气球的序号。如果 i - 1或 i + 1 超出了数组的边界,那么就当它是一个数字为 1 的气球。
求所能获得硬币的最大数量。
示例 1:
输入:nums = [3,1,5,8] 输出:167 解释: nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> [] coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167
示例 2:
输入:nums = [1,5] 输出:10
提示:
n == nums.length1 <= n <= 3000 <= nums[i] <= 100
解题思路
方法一:动态规划
我们记数组 的长度为 。根据题目描述,我们可以在数组 的左右两端各添加一个 ,记为 。
然后,我们定义 表示戳破区间 内的所有气球能得到的最多硬币数,那么答案即为 。
对于 ,我们枚举区间 内的所有位置 ,假设 是最后一个戳破的气球,那么我们可以得到如下状态转移方程:
在实现上,由于 的状态转移方程中涉及到 和 ,其中 ,因此我们需要从大到小地遍历 ,从小到大地遍历 ,这样才能保证当计算 时 和 已经被计算出来。
最后,我们返回 即可。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
class Solution:
def maxCoins(self, nums: List[int]) -> int:
n = len(nums)
arr = [1] + nums + [1]
f = [[0] * (n + 2) for _ in range(n + 2)]
for i in range(n - 1, -1, -1):
for j in range(i + 2, n + 2):
for k in range(i + 1, j):
f[i][j] = max(f[i][j], f[i][k] + f[k][j] + arr[i] * arr[k] * arr[j])
return f[0][-1]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n^3) due to iterating all subarrays and possible last balloons within each. Space complexity is O(n^2) for the DP table storing maximum coins for all ranges. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Expect discussion of recursive state definition versus iterative DP filling.
- question_mark
Look for correct handling of boundary conditions using virtual balloons of value 1.
- question_mark
Check awareness of overlapping subproblems and use of memoization or DP table.
常见陷阱
外企场景- error
Forgetting to pad nums with 1 at both ends leading to index errors.
- error
Incorrectly defining DP state, such as including endpoints instead of exclusive ranges.
- error
Neglecting to iterate all possible last-burst positions within a subarray.
进阶变体
外企场景- arrow_right_alt
Maximizing coins when balloons can have negative numbers, requiring careful multiplication handling.
- arrow_right_alt
Bursting balloons with additional constraints, e.g., only adjacent balloons can be burst next.
- arrow_right_alt
Adapting the DP approach to count number of distinct maximum-coin sequences.