![]() |
VOOZH | about |
Given n dices each with m faces, numbered from 1 to m, the task is to find the number of ways to get sum x. x is the summation of values on each face when all the dice are thrown.
Examples:
Input: m = 6, n = 3, x = 12
Output: 25
Explanation: There are 25 total ways to get the Sum 12 using 3 dices with faces from 1 to 6.Input: m = 2, n = 3, x = 6
Output: 1
Explanation: There is only 1 way to get the Sum 6 using 3 dices with faces from 1 to 2. All the dices will have to land on 2.
Table of Content
The idea is to explore all possible ways to achieve the target sum. For each die, the approach tries every possible face value (from 1 to m), and recursively checks the number of ways to achieve the remaining sum with the remaining dice. At each recursive step, the function reduces the number of dice by one and subtracts the current die's value from the target sum. Base cases handle scenarios where all dice have been used or the target sum cannot be achieved, returning 1 for a valid combination and 0 for invalid scenarios.
Mathematically the recurrence relation will look like the following:
- noOfWays(m, n, x) = sum (noOfWays(m, n-1, x-j)) for j in range[1, m].
Base Cases:
- noOfWays(m, n, x) = 1, if n = 0 and x = 0.
- noOfWays(m, n, x) = 0, if n = 0 or x < 0.
21
If we notice carefully, we can observe that the above recursive solution holds the following two properties of Dynamic Programming:
1. Optimal Substructure: Number of ways to make sum at dice n, i.e., noOfWays(m, n, x), depends on the solutions of the subproblems noOfWays(m, n-1, x-j) for j in range [1, m]. By combining these optimal substructures, we can efficiently calculate the number of ways to make target sum at dice n.
2. Overlapping Subproblems: While applying a recursive approach in this problem, we notice that certain subproblems are computed multiple times.
21
The idea is to fill the DP table based on previous values. For each dice i and sum j, we try all the values k from 1 to m. The table is filled in an iterative manner from i = 1 to i = n and for each sum j from 1 to x.
The dynamic programming relation is as follows:
- dp[i][j] = sum(dp[i-1][j-k]) where k is in range [1, m] and j-k >= 0.
21
In previous approach of dynamic programming we have derive the relation between states as given below:
- dp[i][j] = sum(dp[i-1][j-k]) where k is in range [1, m] and j-k >= 0.
If we observe that for calculating current dp[i][j] state we only need previous row. There is no need to store all the previous states just one previous state is used to compute result.
21