LeetCode 题解工作台
给小朋友们分糖果 I
给你两个正整数 n 和 limit 。 请你将 n 颗糖果分给 3 位小朋友,确保没有任何小朋友得到超过 limit 颗糖果,请你返回满足此条件下的 总方案数 。 示例 1: 输入: n = 5, limit = 2 输出: 3 解释: 总共有 3 种方法分配 5 颗糖果,且每位小朋友的糖果数不超过…
3
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数学·结合·combinatorics
答案摘要
根据题目描述,我们需要将 个糖果分给 个小孩,每个小孩分到的糖果数在 $[0, limit]$ 之间。 这实际上等价于把 个球放入 个盒子中。由于盒子可以为空,我们可以再增加 个虚拟球,然后再利用隔板法,即一共有 $n + 3$ 个球,我们在其中 $n + 3 - 1$ 个位置插入 个隔板,从而将实际的 个球分成 组,并且允许盒子为空,因此初始方案数为 $C_{n + 2}^2$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·结合·combinatorics 题型思路
题目描述
给你两个正整数 n 和 limit 。
请你将 n 颗糖果分给 3 位小朋友,确保没有任何小朋友得到超过 limit 颗糖果,请你返回满足此条件下的 总方案数 。
示例 1:
输入:n = 5, limit = 2 输出:3 解释:总共有 3 种方法分配 5 颗糖果,且每位小朋友的糖果数不超过 2 :(1, 2, 2) ,(2, 1, 2) 和 (2, 2, 1) 。
示例 2:
输入:n = 3, limit = 3 输出:10 解释:总共有 10 种方法分配 3 颗糖果,且每位小朋友的糖果数不超过 3 :(0, 0, 3) ,(0, 1, 2) ,(0, 2, 1) ,(0, 3, 0) ,(1, 0, 2) ,(1, 1, 1) ,(1, 2, 0) ,(2, 0, 1) ,(2, 1, 0) 和 (3, 0, 0) 。
提示:
1 <= n <= 501 <= limit <= 50
解题思路
方法一:组合数学 + 容斥原理
根据题目描述,我们需要将 个糖果分给 个小孩,每个小孩分到的糖果数在 之间。
这实际上等价于把 个球放入 个盒子中。由于盒子可以为空,我们可以再增加 个虚拟球,然后再利用隔板法,即一共有 个球,我们在其中 个位置插入 个隔板,从而将实际的 个球分成 组,并且允许盒子为空,因此初始方案数为 。
我们需要在这些方案中,排除掉存在盒子分到的小球数超过 的方案。考虑其中有一个盒子分到的小球数超过 ,那么剩下的球(包括虚拟球)最多有 个,位置数为 ,因此方案数为 。由于存在 个盒子,因此这样的方案数为 。这样子算,我们会多排除掉同时存在两个盒子分到的小球数超过 的方案,因此我们需要再加上这样的方案数,即 。
时间复杂度 ,空间复杂度 。
class Solution:
def distributeCandies(self, n: int, limit: int) -> int:
if n > 3 * limit:
return 0
ans = comb(n + 2, 2)
if n > limit:
ans -= 3 * comb(n - limit + 1, 2)
if n - 2 >= 2 * limit:
ans += 3 * comb(n - 2 * limit, 2)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate suggests an efficient combinatorial approach.
- question_mark
Candidate considers dynamic programming for optimization.
- question_mark
Candidate does not consider the brute-force method but instead tries an optimized solution.
常见陷阱
外企场景- error
Forgetting to check that the sum of candies matches n.
- error
Incorrectly counting distributions where children receive more than the limit.
- error
Overcomplicating the problem with unnecessary optimizations before checking the brute-force solution.
进阶变体
外企场景- arrow_right_alt
Varying the number of children to test scalability.
- arrow_right_alt
Adjusting the limit per child to explore edge cases.
- arrow_right_alt
Considering the possibility of using more advanced combinatorics techniques to optimize the solution.