Problem Description
Given n dice, each having k faces numbered from 1 to k, determine the number of ways to roll the dice such that the sum of the top faces equals target. Since the answer can be very large, return the result modulo 10^9 + 7.
Key Insights
- Use dynamic programming to build the solution iteratively.
- Define dp[i][j] as the number of ways to achieve sum j using i dice.
- The base case is dp[0][0] = 1, representing one way to achieve a sum of 0 using 0 dice.
- For each die, consider all possible face values from 1 to k, and update the dp table accordingly.
- Only update for sums that remain within the target.
- The final answer will be stored in dp[n][target] modulo 10^9 + 7.
Space and Time Complexity
Time Complexity: O(n * target * k)
Space Complexity: O(target) if optimized using a one-dimensional dp array.
Solution
We solve the problem using a dynamic programming approach. A one-dimensional dp array is maintained where dp[j] represents the number of ways to obtain the sum j using the current number of dice. We start with dp[0] = 1 since there is exactly one way to achieve a sum of 0 without using any dice. For each dice, a new dp array is computed by iterating over every possible current sum and adding each possible dice face value (from 1 to k) if the new sum does not exceed target. By repeatedly updating the dp array, we obtain the final count in dp[target] after processing all dice. We take every update modulo 10^9 + 7 to handle large numbers.