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.
思路:dp[i][j] 表示 用了i个筛子,能够得到和为j的 possible ways是多少;
class Solution {
private int MOD = 1000000007;
public int numRollsToTarget(int d, int f, int target) {
if(d <= 0 || f <= 0 || target <= 0) {
return 0;
}
int[][] dp = new int[d + 1][target + 1];
for(int i = 0; i <= d; i++) {
for(int j = 0; j <= target; j++) {
if(i == 0 && j == 0) {
dp[i][j] = 1;
} else {
for(int k = 1; k <= f; k++) {
if(i - 1 >= 0 && j - k >= 0)
dp[i][j] = (dp[i][j] % MOD + dp[i - 1][j - k] % MOD) % MOD;
}
}
}
}
return dp[d][target];
}
}
DFS + Memo, 有两个变化的维度,一个是d,一个是target;[1, f];
class Solution {
private int MOD = 1000000007;
public int numRollsToTarget(int d, int f, int target) {
if(d <= 0 || f <= 0 || target <= 0) {
return 0;
}
Integer[][] cache = new Integer[d + 1][target + 1];
return dfs(d, f, target, cache);
}
private int dfs(int d, int f, int target, Integer[][] cache) {
if(d < 0 || target < 0) {
return 0;
}
if(d == 0) {
return target == 0 ? 1 : 0;
}
if(cache[d][target] != null) {
return cache[d][target];
}
int value = 0;
for(int k = 1; k <= f; k++) {
value = (value % MOD + dfs(d - 1, f, target - k, cache) % MOD) % MOD;
}
cache[d][target] = value;
return cache[d][target];
}
}