-
Notifications
You must be signed in to change notification settings - Fork 2
/
NumberOfDiceRollsWithTargetSum.java
84 lines (76 loc) · 2.07 KB
/
NumberOfDiceRollsWithTargetSum.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package Leetcode;
/**
* @author kalpak
*
* You have d dice, and each die has f faces numbered 1, 2, ..., f.
*
* Return the number of possible ways (out of fd total ways) modulo 10^9 + 7 to roll the dice so the sum of the face up numbers equals target.
*
*
* Example 1:
* Input: d = 1, f = 6, target = 3
* Output: 1
* Explanation:
* You throw one die with 6 faces. There is only one way to get a sum of 3.
*
*
* Example 2:
* Input: d = 2, f = 6, target = 7
* Output: 6
* Explanation:
* You throw two dice, each with 6 faces. There are 6 ways to get a sum of 7:
* 1+6, 2+5, 3+4, 4+3, 5+2, 6+1.
*
*
* Example 3:
* Input: d = 2, f = 5, target = 10
* Output: 1
* Explanation:
* You throw two dice, each with 5 faces. There is only one way to get a sum of 10: 5+5.
*
*
* Example 4:
* Input: d = 1, f = 2, target = 3
* Output: 0
* Explanation:
* You throw one die with 2 faces. There is no way to get a sum of 3.
*
*
* Example 5:
* Input: d = 30, f = 30, target = 500
* Output: 222616187
* Explanation:
* The answer must be returned modulo 10^9 + 7.
*
*
* Constraints:
*
* 1 <= d, f <= 30
* 1 <= target <= 1000
*
*/
public class NumberOfDiceRollsWithTargetSum {
final static int MOD = 1000000007;
public static int numRollsToTarget(int d, int f, int target) {
int[][] dp = new int[d + 1][target + 1];
// dp[i][j] means how many ways that using i dices to sum to target j.
// And the state function is
// dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j - 2] + ... + dp[i - 1][j - k].
dp[0][0] = 1;
for (int i = 1; i <= d; i++) {
for (int j = 0; j <= target; j++) {
if (target > f * d)
continue;
for (int k = 1; k <= f; k++) {
if (j - k >= 0) {
dp[i][j] = (dp[i][j] + dp[i - 1][j - k]) % MOD;
}
}
}
}
return dp[d][target];
}
public static void main(String[] args) {
System.out.println(numRollsToTarget(1, 6, 3));
}
}