LeetCode 题解工作台
放置盒子
有一个立方体房间,其长度、宽度和高度都等于 n 个单位。请你在房间里放置 n 个盒子,每个盒子都是一个单位边长的立方体。放置规则如下: 你可以把盒子放在地板上的任何地方。 如果盒子 x 需要放置在盒子 y 的顶部,那么盒子 y 竖直的四个侧面都 必须 与另一个盒子或墙相邻。 给你一个整数 n ,返回…
3
题型
4
代码语言
3
相关题
当前训练重点
困难 · 二分·搜索·答案·空间
答案摘要
根据题目描述,层数最高的盒子需要放在墙角,并且盒子的摆放呈阶梯状,这样可以使得接触地面的盒子数量最少。 假设盒子摆放 层,从上到下,每一层如果摆满,那么个数分别是 $1, 1+2, 1+2+3, \cdots, 1+2+\cdots+k$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
有一个立方体房间,其长度、宽度和高度都等于 n 个单位。请你在房间里放置 n 个盒子,每个盒子都是一个单位边长的立方体。放置规则如下:
- 你可以把盒子放在地板上的任何地方。
- 如果盒子
x需要放置在盒子y的顶部,那么盒子y竖直的四个侧面都 必须 与另一个盒子或墙相邻。
给你一个整数 n ,返回接触地面的盒子的 最少 可能数量。
示例 1:

输入:n = 3 输出:3 解释:上图是 3 个盒子的摆放位置。 这些盒子放在房间的一角,对应左侧位置。
示例 2:

输入:n = 4 输出:3 解释:上图是 3 个盒子的摆放位置。 这些盒子放在房间的一角,对应左侧位置。
示例 3:

输入:n = 10 输出:6 解释:上图是 10 个盒子的摆放位置。 这些盒子放在房间的一角,对应后方位置。
提示:
1 <= n <= 109
解题思路
方法一:数学规律
根据题目描述,层数最高的盒子需要放在墙角,并且盒子的摆放呈阶梯状,这样可以使得接触地面的盒子数量最少。
假设盒子摆放 层,从上到下,每一层如果摆满,那么个数分别是 。
如果此时盒子还有剩余,那么可以从最低一层继续摆放,假设摆放 个,那么累计可摆放的盒子个数为 。
时间复杂度 ,其中 为题目给定的盒子数量。空间复杂度 。
class Solution:
def minimumBoxes(self, n: int) -> int:
s, k = 0, 1
while s + k * (k + 1) // 2 <= n:
s += k * (k + 1) // 2
k += 1
k -= 1
ans = k * (k + 1) // 2
k = 1
while s < n:
ans += 1
s += k
k += 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Able to identify the correct application of binary search over the solution space.
- question_mark
Can describe the use of greedy algorithms to optimize floor placement.
- question_mark
Comfortable with applying mathematical reasoning to break down the box placement in a cubic space.
常见陷阱
外企场景- error
Overlooking the binary search's application to the answer space, leading to inefficiency.
- error
Failing to properly apply greedy placement to maximize the use of space.
- error
Not considering mathematical relationships that govern how boxes can fit in the room.
进阶变体
外企场景- arrow_right_alt
Consider modifying the constraints by increasing n to test scalability.
- arrow_right_alt
Explore different ways of calculating box placement, considering different room dimensions.
- arrow_right_alt
Alter the number of boxes to be placed in the room to create varied test cases.