728. Dice to a Total

Medium3.5 points estimatedDynamic Programming3 hints

You roll n fair dice at once, and every die has k faces numbered 1 through k. The dice are distinguishable, so the outcome (die A shows 1, die B shows 2) differs from (die A shows 2, die B shows 1).

Return the number of distinct outcomes in which the faces showing add up to exactly target. If the total cannot be reached, for instance when target is less than n or more than n * k, return 0.

The count may be huge, so return it modulo 1000000007. Aim for time O(n * target) (a sliding window over the previous row avoids an extra factor of k) and space O(target).

Example 1

Input:
n = 3, k = 4, target = 9
Output:
10
Explanation:

The faces (1,4,4) give 3 orders, (2,3,4) gives 6 orders and (3,3,3) gives 1, so 3 + 6 + 1 = 10 outcomes total 9.

Example 2

Input:
n = 4, k = 3, target = 13
Output:
0
Explanation:

Four three-sided dice have a maximum total of 12, so 13 is impossible and the answer is 0.

Constraints

1 ≤ n ≤ 50

1 ≤ k ≤ 50

1 ≤ target ≤ 2500

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n * target)
Space
O(target)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…