[leetcode] 1155. Number of Dice Rolls With Target Sum

Description

You have d dice, and each die has f faces numbered 1, 2, …, f.

Return the number of possible ways (out of fd total ways) modulo 10^9 + 7 to roll the dice so the sum of the face up numbers equals target.

Example 1:

Input: d = 1, f = 6, target = 3
Output: 1
Explanation: 
You throw one die with 6 faces.  There is only one way to get a sum of 3.

Example 2:

Input: d = 2, f = 6, target = 7
Output: 6
Explanation: 
You throw two dice, each with 6 faces.  There are 6 ways to get a sum of 7:
1+6, 2+5, 3+4, 4+3, 5+2, 6+1.

Example 3:

Input: d = 2, f = 5, target = 10
Output: 1
Explanation: 
You throw two dice, each with 5 faces.  There is only one way to get a sum of 10: 5+5.

Example 4:

Input: d = 1, f = 2, target = 3
Output: 0
Explanation: 
You throw one die with 2 faces.  There is no way to get a sum of 3.

Example 5:

Input: d = 30, f = 30, target = 500
Output: 222616187
Explanation: 
The answer must be returned modulo 10^9 + 7.

Constraints:

  • 1 <= d, f <= 30
  • 1 <= target <= 1000

分析

题目的意思是:给定一个骰子,规定了掷骰子的次数和骰子的点数范围,求能够达到target的组合数。

  1. 设dp[i][j]表示掷了前i个骰子,得到总和数位为j的方案数。
  2. 初始时,dp[0][0]=1,表示没有掷骰子时,得到的总方案数是1。
  3. 枚举掷骰子的点数,得到递推公式
dp[i][k]=dp[i][k]+dp[i-1][k-j]

意思是用i个骰子达到k等于i-1个骰子达到k-j的和,其中j从1到f
4.最后答案为dp[d][target]

代码

class Solution:
    def numRollsToTarget(self, d: int, f: int, target: int) -> int:
        dp=[[0]*(target+1) for i in range(d+1)]
        dp[0][0]=1
        for i in range(1,d+1):
            for j in range(1,f+1):
                for k in range(j,target+1):
                    dp[i][k]=(dp[i][k]+dp[i-1][k-j])%(10**9+7)
        return dp[d][target]

参考文献

LeetCode 1155. Number of Dice Rolls With Target Sum

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值