LeetCode 题解工作台
香槟塔
我们把玻璃杯摆成金字塔的形状,其中 第一层 有 1 个玻璃杯, 第二层 有 2 个,依次类推到第 100 层,每个玻璃杯将盛有香槟。 从顶层的第一个玻璃杯开始倾倒一些香槟,当顶层的杯子满了,任何溢出的香槟都会立刻等流量的流向左右两侧的玻璃杯。当左右两边的杯子也满了,就会等流量的流向它们左右两边的杯子…
1
题型
6
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们直接模拟倒香槟的过程。 定义一个二维数组 ,其中 表示第 层第 个玻璃杯中的香槟量。初始时 $f[0][0] = poured$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
我们把玻璃杯摆成金字塔的形状,其中 第一层 有 1 个玻璃杯, 第二层 有 2 个,依次类推到第 100 层,每个玻璃杯将盛有香槟。
从顶层的第一个玻璃杯开始倾倒一些香槟,当顶层的杯子满了,任何溢出的香槟都会立刻等流量的流向左右两侧的玻璃杯。当左右两边的杯子也满了,就会等流量的流向它们左右两边的杯子,依次类推。(当最底层的玻璃杯满了,香槟会流到地板上)
例如,在倾倒一杯香槟后,最顶层的玻璃杯满了。倾倒了两杯香槟后,第二层的两个玻璃杯各自盛放一半的香槟。在倒三杯香槟后,第二层的香槟满了 - 此时总共有三个满的玻璃杯。在倒第四杯后,第三层中间的玻璃杯盛放了一半的香槟,他两边的玻璃杯各自盛放了四分之一的香槟,如下图所示。

现在当倾倒了非负整数杯香槟后,返回第 i 行 j 个玻璃杯所盛放的香槟占玻璃杯容积的比例( i 和 j 都从0开始)。
示例 1: 输入: poured(倾倒香槟总杯数) = 1, query_glass(杯子的位置数) = 1, query_row(行数) = 1 输出: 0.00000 解释: 我们在顶层(下标是(0,0))倒了一杯香槟后,没有溢出,因此所有在顶层以下的玻璃杯都是空的。 示例 2: 输入: poured(倾倒香槟总杯数) = 2, query_glass(杯子的位置数) = 1, query_row(行数) = 1 输出: 0.50000 解释: 我们在顶层(下标是(0,0)倒了两杯香槟后,有一杯量的香槟将从顶层溢出,位于(1,0)的玻璃杯和(1,1)的玻璃杯平分了这一杯香槟,所以每个玻璃杯有一半的香槟。
示例 3:
输入: poured = 100000009, query_row = 33, query_glass = 17 输出: 1.00000
提示:
0 <= poured <= 1090 <= query_glass <= query_row < 100
解题思路
方法一:模拟
我们直接模拟倒香槟的过程。
定义一个二维数组 ,其中 表示第 层第 个玻璃杯中的香槟量。初始时 。
对于每一层,如果当前杯子的香槟量 大于 ,香槟会流向下一层的两个杯子,流入的量为 ,即当前杯子的香槟量减去 后除以 ,然后当前杯子的香槟量更新为 。
模拟结束,返回 即可。
时间复杂度 ,空间复杂度 。其中 为层数,即 。
class Solution:
def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float:
f = [[0] * 101 for _ in range(101)]
f[0][0] = poured
for i in range(query_row + 1):
for j in range(i + 1):
if f[i][j] > 1:
half = (f[i][j] - 1) / 2
f[i][j] = 1
f[i + 1][j] += half
f[i + 1][j + 1] += half
return f[query_row][query_glass]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(R^2) since every glass up to the query row is processed once. Space complexity is O(R^2) to store DP states for all glasses up to the query row. |
| 空间 | O(R^2) |
面试官常问的追问
外企场景- question_mark
Emphasize using dynamic programming to track cascading state transitions in the pyramid.
- question_mark
Look for correct handling of overflow splitting exactly half to each child glass.
- question_mark
Notice if the candidate caps values at 1 per glass instead of summing total overflow incorrectly.
常见陷阱
外企场景- error
Failing to distribute overflow correctly, leading to inaccurate amounts in lower glasses.
- error
Not capping the queried glass at 1, returning more than the glass can hold.
- error
Attempting a recursive solution without memoization, causing excessive computation.
进阶变体
外企场景- arrow_right_alt
Compute total full glasses after pouring a given amount, leveraging the same DP overflow approach.
- arrow_right_alt
Determine the first glass to overflow beyond 1 cup in a large poured scenario using DP simulation.
- arrow_right_alt
Optimize space by using a single-row rolling DP array for large query_row values.