Number of Dice Rolls With Target Sum

You have n dice, and each die has k faces numbered from 1 to k. Given three integers n, k, and target, return the number of possible ways (out of the k^n total ways) to roll the dice so the sum of the face-up numbers equals target. Since the answer may be too large, return it modulo 10^9 + 7.

30:00

Number of Dice Rolls With Target Sum
medium
Free written solution
Topics
Companies

You have n dice, and each die has k faces numbered from 1 to k. Given three integers n, k, and target, return the number of possible ways (out of the k^n total ways) to roll the dice so the sum of the face-up numbers equals target. Since the answer may be too large, return it modulo 10^9 + 7.

Example 1:
Input: {"n":1,"k":6,"target":3}
Output: 1
Constraints:
  • 1≤n,k≤301 \leq n, k \leq 30

  • 1≤target≤10001 \leq \text{target} \leq 1000

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"n":1,"k":6,"target":3}

Row 0 is "no dice rolled yet": the only reachable sum is 0, in exactly one way. dp[0] = 1 and every other sum is 0.

1 dice, faces 1..6, target 3

1

rows = dice used, columns = sum

0
1
2
3
0d
1
0
0
0
1d

fN = previous row cell reached when the new die shows N

target column

Variables
VariableValue
n1
k6
target3
DepthFunction Call
Stack empty
0/5