题目描述
A die simulator generates a random number from 1 to 6 for each roll. You introduced a constraint to the generator such that it cannot roll the number i more than rollMax[i] (1-indexed) consecutive times.
Given an array of integers rollMax and an integer n, return the number of distinct sequences that can be obtained with exact n rolls.
Two sequences are considered different if at least one element differs from each other. Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: n = 2, rollMax = [1,1,2,2,2,3]
Output: 34
Explanation: There will be 2 rolls of die, if there are no constraints on the die, there are 6 * 6 = 36 possible combinations. In this case, looking at rollMax array, the numbers 1 and 2 appear at most once consecutively, therefore sequences (1,1) and (2,2) cannot occur, so the final answer is 36-2 = 34.
Example 2:
Input: n = 2, rollMax = [1,1,1,1,1,1]
Output: 30
Example 3:
Input: n = 3, rollMax = [1,1,1,2,2,3]
Output: 181
Constraints:
1 <= n <= 5000
rollMax.length == 6
1 <= rollMax[i] <= 15
思路
动态规划。dp[i][j][k]表示长度为i的序列,以j结尾,最后一个数字连续k次,的序列个数。
dp[i][j][k] += dp[i-1][j][k-1]。
dp[i][j][1] += sum(dp[i-1][m][k]) (m != j and k ∈ (1, max[m])。
自己闷出了这个三维dp,看题解可以压缩到二维,就是计算有点绕。不想写了。
代码
class Solution {
public:
int dieSimulator(int n, vector<int>& rollMax) {
int MOD = 1e9+7;
vector<vector<vector<int>>> dp(n+1, vector<vector<int>>(6+1, vector<int>(15+1, 0)));
for (int i=1; i<=6; ++i) dp[1][i][1] = 1;
for (int i=2; i<=n; ++i) {
for (int j=1; j<=6; ++j) {
for (int k=rollMax[j-1]; k>1; --k) {
dp[i][j][k] += dp[i-1][j][k-1];
dp[i][j][k] %= MOD;
}
for (int k=1; k<=6; ++k) {
if (j == k) continue;
for (int s=rollMax[k-1]; s>=1; --s) {
dp[i][j][1] += dp[i-1][k][s];
dp[i][j][1] %= MOD;
}
}
}
}
int res = 0;
for (int i=1; i<=6; ++i) {
for (int j=1; j<=rollMax[i-1]; ++j) {
res += dp[n][i][j];
res %= MOD;
}
}
return res;
}
};
在外边待了一天,八点多才回来
烦。。。
生活就是一地鸡毛啊。
这种时候想谈恋爱,就可以有个人说说话了。