LeetCode 题解工作台
掷骰子等于目标和的方法数
这里有 n 个一样的骰子,每个骰子上都有 k 个面,分别标号为 1 到 k 。 给定三个整数 n 、 k 和 target ,请返回投掷骰子的所有可能得到的结果(共有 k n 种方式),使得骰子面朝上的数字总和等于 target 。 由于答案可能很大,你需要对 10 9 + 7 取模 。 示例 1:…
1
题型
6
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们定义 表示使用 个骰子,和为 的方案数。那么我们可以得到状态转移方程: $$
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
这里有 n 个一样的骰子,每个骰子上都有 k 个面,分别标号为 1 到 k 。
给定三个整数 n、k 和 target,请返回投掷骰子的所有可能得到的结果(共有 kn 种方式),使得骰子面朝上的数字总和等于 target。
由于答案可能很大,你需要对 109 + 7 取模。
示例 1:
输入:n = 1, k = 6, target = 3 输出:1 解释:你掷了一个有 6 个面的骰子。 得到总和为 3 的结果的方式只有一种。
示例 2:
输入:n = 2, k = 6, target = 7 输出:6 解释:你掷了两个骰子,每个骰子有 6 个面。 有 6 种方式得到总和为 7 的结果: 1+6, 2+5, 3+4, 4+3, 5+2, 6+1。
示例 3:
输入:n = 30, k = 30, target = 500 输出:222616187 解释:返回的结果必须对 109 + 7 取模。
提示:
1 <= n, k <= 301 <= target <= 1000
解题思路
方法一:动态规划
我们定义 表示使用 个骰子,和为 的方案数。那么我们可以得到状态转移方程:
其中 表示第 个骰子的点数。
初始时 ,最终的答案即为 。
时间复杂度 ,空间复杂度 。
我们注意到,状态 只和 有关,因此我们可以使用滚动数组的方式,将空间复杂度优化到 。
class Solution:
def numRollsToTarget(self, n: int, k: int, target: int) -> int:
f = [[0] * (target + 1) for _ in range(n + 1)]
f[0][0] = 1
mod = 10**9 + 7
for i in range(1, n + 1):
for j in range(1, min(i * k, target) + 1):
for h in range(1, min(j, k) + 1):
f[i][j] = (f[i][j] + f[i - 1][j - h]) % mod
return f[n][target]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n * target * k) because for each of n dice and each intermediate sum up to target, we iterate over k faces. Space complexity is O(n * target) for the DP table, which can be optimized to O(target) using rolling arrays. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate should recognize the state definition as remaining dice and current sum.
- question_mark
The interviewer may check whether the solution handles large numbers with modulo 10^9 + 7.
- question_mark
Expect discussion of DP optimization to reduce space using a rolling array for sums.
常见陷阱
外企场景- error
Forgetting to apply modulo at each update, causing integer overflow.
- error
Incorrectly defining the DP state or transitions, leading to overcounting or missed sequences.
- error
Attempting brute-force recursion without memoization, which exceeds time limits.
进阶变体
外企场景- arrow_right_alt
Count sequences where dice have non-uniform faces or different ranges.
- arrow_right_alt
Find the probability of rolling a sum rather than counting sequences.
- arrow_right_alt
Determine the minimum number of dice needed to reach at least the target sum.