LeetCode 题解工作台
播放列表的数量
你的音乐播放器里有 n 首不同的歌,在旅途中,你计划听 goal 首歌(不一定不同,即,允许歌曲重复)。你将会按如下规则创建播放列表: 每首歌 至少播放一次 。 一首歌只有在其他 k 首歌播放完之后才能再次播放。 给你 n 、 goal 和 k ,返回可以满足要求的播放列表的数量。由于答案可能非常大…
3
题型
6
代码语言
3
相关题
当前训练重点
困难 · 状态·转移·动态规划
答案摘要
我们定义 表示听 首歌,且这 首歌中有 首不同歌曲的播放列表的数量。初始时 。答案为 。 对于 ,我们可以选择没听过的歌,那么上一个状态为 $f[i - 1][j - 1]$,这样的选择有 $n - (j - 1) = n - j + 1$ 种,因此 $f[i][j] += f[i - 1][j - 1] \times (n - j + 1)$。我们也可以选择听过的歌,那么上一个状态为 $…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
你的音乐播放器里有 n 首不同的歌,在旅途中,你计划听 goal 首歌(不一定不同,即,允许歌曲重复)。你将会按如下规则创建播放列表:
- 每首歌 至少播放一次 。
- 一首歌只有在其他
k首歌播放完之后才能再次播放。
给你 n、goal 和 k ,返回可以满足要求的播放列表的数量。由于答案可能非常大,请返回对 109 + 7 取余 的结果。
示例 1:
输入:n = 3, goal = 3, k = 1 输出:6 解释:有 6 种可能的播放列表。[1, 2, 3],[1, 3, 2],[2, 1, 3],[2, 3, 1],[3, 1, 2],[3, 2, 1] 。
示例 2:
输入:n = 2, goal = 3, k = 0 输出:6 解释:有 6 种可能的播放列表。[1, 1, 2],[1, 2, 1],[2, 1, 1],[2, 2, 1],[2, 1, 2],[1, 2, 2] 。
示例 3:
输入:n = 2, goal = 3, k = 1 输出:2 解释:有 2 种可能的播放列表。[1, 2, 1],[2, 1, 2] 。
提示:
0 <= k < n <= goal <= 100
解题思路
方法一:动态规划
我们定义 表示听 首歌,且这 首歌中有 首不同歌曲的播放列表的数量。初始时 。答案为 。
对于 ,我们可以选择没听过的歌,那么上一个状态为 ,这样的选择有 种,因此 。我们也可以选择听过的歌,那么上一个状态为 ,这样的选择有 种,因此 ,其中 。
综上,我们可以得到状态转移方程:
最终的答案为 。
时间复杂度 ,空间复杂度 。其中 和 为题目中给定的参数。
class Solution:
def numMusicPlaylists(self, n: int, goal: int, k: int) -> int:
mod = 10**9 + 7
f = [[0] * (n + 1) for _ in range(goal + 1)]
f[0][0] = 1
for i in range(1, goal + 1):
for j in range(1, n + 1):
f[i][j] = f[i - 1][j - 1] * (n - j + 1)
if j > k:
f[i][j] += f[i - 1][j] * (j - k)
f[i][j] %= mod
return f[goal][n]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n \log \text{goal}) |
| 空间 | O(n) |
面试官常问的追问
外企场景- question_mark
The candidate demonstrates an understanding of dynamic programming and modular arithmetic.
- question_mark
The candidate can clearly explain the logic behind state transitions and playlist constraints.
- question_mark
The candidate is able to optimize a combinatorial counting problem using dynamic programming techniques.
常见陷阱
外企场景- error
Misunderstanding the modular arithmetic and failing to apply modulo 10^9 + 7 correctly.
- error
Incorrectly handling the case where no songs can be repeated within k songs, especially when constructing the DP table.
- error
Overlooking the fact that playlist lengths must exactly equal goal, which can lead to edge case errors when calculating the result.
进阶变体
外企场景- arrow_right_alt
Handling larger values of n and goal, which increases the complexity of the state transitions and the time required to compute the result.
- arrow_right_alt
Adapting the problem to include additional constraints such as a maximum number of distinct songs in the playlist.
- arrow_right_alt
Solving the problem in a distributed manner where the DP states can be computed concurrently.