1 题目
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
.
2 尝试解
2.1 分析
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
一个骰子掷n次,其中rollMax(i)表示i+1最多连续出现的次数,如rollMax[0]=2表示1最多连续出现两次,超过则本次投掷无效,重新投掷直到掷出非1的数字。问在满足上述要求的情况下,投掷n次一共会出现多少种情况。
3 标准解
3.1 分析
dp[i][j]表示第i次投掷,掷出数字j的所有可能情况的次数。
如果i <= rollMax[j],则上一次投掷可以掷出任何数字,dp[i][j] = sum(dp[i-1][k] for k in range(6))。dp[1][j] = (rollMax[j]>0?1:0)。
如果i == rollMax[j] + 1,则本次投掷如果要掷出j,那么前i-1次就不能全部为j,否则超出限制,所以dp[i][j] = sum(dp[i-1][k] for k in range(6)) - 1。即之前rollMax[j]次投掷全部掷出j只可能有1中情况。
如果i > rollMax[j] + 1, 则本次投掷如果要掷出j,那么第i-rollMax[j]到i-1次就不能全部掷出j。这些情况为第i-rollMax[j]-1没有掷出j,且之后的rollMax[j]次全部掷出j,将这些情况除去即可。所以dp[i][j] = sum(dp[i-1][k] for k in range(6)) - sum(dp[i-rollMax[j]-1][k] for k in range(6) - dp[i-rollMax[j]-1][j])。
3.2 代码
class Solution {
public:
int dieSimulator(int n, vector<int>& rollMax) {
long base = int(10e8)+7;
vector<vector<long>> dp(n+1,vector<long>(7,0));
for(int i = 1; i <= n; i++){
for(int j = 0; j < 6; j++){
if(i == 1 && rollMax[j] > 0)
dp[i][j] = 1;
else if(i <= rollMax[j])
dp[i][j] = dp[i-1][6];
else{
if(i-rollMax[j] == 1)
dp[i][j] = dp[i-1][6]-1;
else{
dp[i][j] = dp[i-1][6]-(dp[i-rollMax[j]-1][6]-dp[i-rollMax[j]-1][j])%base;
if(dp[i][j] < 0)
dp[i][j] += base;
}
}
dp[i][6] = (dp[i][6] + dp[i][j]) % base;
}
}
return dp.back().back();
}
};