Leetcode 1155: Number of Dice Rolls With Target Sum

grid47
grid47
Exploring patterns and algorithms
Jul 14, 2024 6 min read

You have n dice, each with k faces numbered from 1 to k. You need to calculate the number of ways to roll the dice such that the sum of the dice equals a target value. Return the result modulo (10^9 + 7).
Problem
Approach
Steps
Complexity
Input: The input consists of three integers: `n`, `k`, and `target` representing the number of dice, the number of faces on each die, and the target sum, respectively.
Example: Input: [1, 6, 3] Output: 1
Constraints:
• 1 <= n, k <= 30
• 1 <= target <= 1000
Output: The output should be a single integer, representing the number of ways to roll the dice such that their sum equals the target, modulo (10^9 + 7).
Example: Output: 1
Constraints:
• Return the result modulo (10^9 + 7).
Goal: To solve this problem, we will use dynamic programming to count the number of ways to roll the dice such that their sum equals the target.
Steps:
• Initialize a DP table where dp[i][j] represents the number of ways to get a sum of `j` using `i` dice.
• For each die, iterate through all possible face values from 1 to `k` and update the DP table for the target sum.
• Finally, return the value at dp[n][target] after taking modulo (10^9 + 7).
Goal: The solution must handle the constraints of up to 30 dice and target sums as large as 1000 efficiently.
Steps:
• 1 <= n, k <= 30
• 1 <= target <= 1000
Assumptions:
• The dice have faces numbered from 1 to k, with no other numbers on the faces.
• The dice rolls are independent, meaning the result of one die does not affect the others.
Input: Input: [2, 6, 7] Output: 6
Explanation: You have two dice, each with 6 faces. The possible sums to reach 7 are 1+6, 2+5, 3+4, 4+3, 5+2, and 6+1. Hence, the output is 6.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus