Calculate the total number of ways to achieve a given sum with n throws of dice having k faces.

For example,

Input:
 
The total number of throws n is 2
The total number of faces k is 6 (i.e., each dice has values from 1 to 6)
The desired sum is 10
 
Output:
The total number of ways is 3.
 
The possible throws are (6, 4), (4, 6), (5, 5)

Practice this problem

The problem has an optimal substructure as the problem can be broken down into smaller subproblems, which can further be broken down into yet smaller subproblems, and so on.

The idea is to use recursion to solve this problem. We reduce the desired sum by values between 1 and k and recur for the remaining sum with throws left for each throw. If the expected sum is reached with n dices, we have found a way.

The algorithm can be implemented as follows in C, Java, and Python:

C


Download  Run Code

Output:

The total number of ways is 140

Java


Download  Run Code

Output:

The total number of ways is 140

Python


Download  Run Code

Output:

The total number of ways is 140

The time complexity of the above solution is exponential and occupies space in the call stack.

 
The above solution exhibits overlapping subproblems. If we draw the solution’s recursion tree, we can see that the same subproblems are getting computed repeatedly. We know that problems with optimal substructure and overlapping subproblems can be solved using dynamic programming, in which subproblem solutions are memoized rather than computed again and again. The memoized version follows the top-down approach since we first break the problem into subproblems and then calculate and store values.

The approach is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

The total number of ways is 140

Java


Download  Run Code

Output:

The total number of ways is 140

Python


Download  Run Code

Output:

The total number of ways is 140

The time complexity of the above solution is O(n × k × target), and the auxiliary space used by the program is O(n × target).

 
We can also solve this problem in a bottom-up manner. In the bottom-up approach, we solve smaller subproblems first, then solve larger subproblems from them.

 
Exercise: Write bottom-up version of above solution.