|
| 1 | +# 1155. Number of Dice Rolls With Target Sum |
| 2 | + |
| 3 | +- Difficulty: Medium. |
| 4 | +- Related Topics: Dynamic Programming. |
| 5 | +- Similar Questions: Equal Sum Arrays With Minimum Number of Operations, Find Missing Observations. |
| 6 | + |
| 7 | +## Problem |
| 8 | + |
| 9 | +You have `n` dice, and each die has `k` faces numbered from `1` to `k`. |
| 10 | + |
| 11 | +Given three integers `n`, `k`, and `target`, return **the number of possible ways (out of the **`kn`** 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** `109 + 7`. |
| 12 | + |
| 13 | + |
| 14 | +Example 1: |
| 15 | + |
| 16 | +``` |
| 17 | +Input: n = 1, k = 6, target = 3 |
| 18 | +Output: 1 |
| 19 | +Explanation: You throw one die with 6 faces. |
| 20 | +There is only one way to get a sum of 3. |
| 21 | +``` |
| 22 | + |
| 23 | +Example 2: |
| 24 | + |
| 25 | +``` |
| 26 | +Input: n = 2, k = 6, target = 7 |
| 27 | +Output: 6 |
| 28 | +Explanation: You throw two dice, each with 6 faces. |
| 29 | +There are 6 ways to get a sum of 7: 1+6, 2+5, 3+4, 4+3, 5+2, 6+1. |
| 30 | +``` |
| 31 | + |
| 32 | +Example 3: |
| 33 | + |
| 34 | +``` |
| 35 | +Input: n = 30, k = 30, target = 500 |
| 36 | +Output: 222616187 |
| 37 | +Explanation: The answer must be returned modulo 109 + 7. |
| 38 | +``` |
| 39 | + |
| 40 | + |
| 41 | +**Constraints:** |
| 42 | + |
| 43 | + |
| 44 | + |
| 45 | +- `1 <= n, k <= 30` |
| 46 | + |
| 47 | +- `1 <= target <= 1000` |
| 48 | + |
| 49 | + |
| 50 | + |
| 51 | +## Solution |
| 52 | + |
| 53 | +```javascript |
| 54 | +/** |
| 55 | + * @param {number} n |
| 56 | + * @param {number} k |
| 57 | + * @param {number} target |
| 58 | + * @return {number} |
| 59 | + */ |
| 60 | +var numRollsToTarget = function(n, k, target) { |
| 61 | + var dp = Array(n + 1).fill(0).map(() => ({})); |
| 62 | + return helper(n, k, target, dp); |
| 63 | +}; |
| 64 | + |
| 65 | +var helper = function(n, k, target, dp) { |
| 66 | + if (dp[n][target] !== undefined) return dp[n][target]; |
| 67 | + if (n === 0 && target === 0) return 1; |
| 68 | + if (n <= 0 || target <= 0) return 0; |
| 69 | + var res = 0; |
| 70 | + var mod = Math.pow(10, 9) + 7; |
| 71 | + for (var i = 1; i <= k; i++) { |
| 72 | + if (target < i) break; |
| 73 | + res += helper(n - 1, k, target - i, dp); |
| 74 | + res %= mod; |
| 75 | + } |
| 76 | + dp[n][target] = res; |
| 77 | + return res; |
| 78 | +}; |
| 79 | +``` |
| 80 | + |
| 81 | +**Explain:** |
| 82 | + |
| 83 | +nope. |
| 84 | + |
| 85 | +**Complexity:** |
| 86 | + |
| 87 | +* Time complexity : O(n * target). |
| 88 | +* Space complexity : O(n * target). |
0 commit comments