zoukankan      html  css  js  c++  java
  • 【leetcode】1155. Number of Dice Rolls With Target Sum

    题目如下:

    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

    解题思路:记dp[i][j] 为前i个骰子掷完后总和为j的组合的总数。那么很显然(i-1)个骰子掷完后的总和只能是  (j-d)  ~ (j-1) ,所以有dp[i][j] = sum(dp[i-1][j-d] , dp[i-1][j-d + 1] .... + dp[i-1][j-1]) 。

    代码如下:

    class Solution(object):
        def numRollsToTarget(self, d, f, target):
            """
            :type d: int
            :type f: int
            :type target: int
            :rtype: int
            """
            if target > d*f:
                return 0
            dp = [[0] * (d*f+1) for i in range(d)]
            for i in range(1,f+1):
                dp[0][i] = 1
    
            for i in range(1,len(dp)):
                for j in range(len(dp[i])):
                    for k in range(1,f+1):
                        dp[i][j] += dp[i-1][j-k]
            #print dp
    
            return dp[-1][target] % (10**9 + 7)
  • 相关阅读:
    1-wire单总线DS18B20
    开漏输出
    拉电流(source current)与灌电流(sink current)
    高阻态;什么是三态门? 三态逻辑与非门电路以及三态门电路
    小电流MOS管
    DS18B20 CRC8分析
    go hmac使用
    gin入门
    go web框架推荐
    Go语言入门系列2 基本语法
  • 原文地址:https://www.cnblogs.com/seyjs/p/11376741.html
Copyright © 2011-2022 走看看