有一个骰子模拟器会每次投掷的时候生成一个 1 到 6 的随机数。
不过我们在使用它时有个约束,就是使得投掷骰子时,连续 掷出数字 i 的次数不能超过 rollMax[i](i 从 1 开始编号)。
现在,给你一个整数数组 rollMax 和一个整数 n,请你来计算掷 n 次骰子可得到的不同点数序列的数量。
假如两个序列中至少存在一个元素不同,就认为这两个序列是不同的。由于答案可能很大,所以请返回 模 10^9 + 7 之后的结果。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/dice-roll-simulation
动态规划
public static int DieSimulator(int n, int[] rollMax)
{
long[,] dp = new long[n,6];
for (int i = 0; i < 6; i++)
{
dp[0, i] = 1;
}
for (int i = 1; i < n; i++)
{
for (int j = 0; j < 6; j++)
{
long sum = 0;
for (int x = 0; x < 6; x++)
{
sum += dp[i - 1, x];
}
int index = i - rollMax[j];
if (index >= 1)
{
for (int y = 0; y < 6; y++)
{
sum -= dp[index-1, y];
if (sum <= 0) sum += 1000000007;
}
sum += dp[index - 1, j];
}
else if(index==0)
{
sum -= 1;
}
sum %= 1000000007;
dp[i, j] = (int)sum;
}
}
int res = 0;
for (int i = 0; i < 6; i++)
{
res += (int)dp[n - 1, i];
res %= 1000000007;
}
return res;
}
递归
public static int DieSimulator(int n, int[] rollMax)
{
int res = 0;
string temp = "";
int[] again = (int[])rollMax;
myfun(n, rollMax, again, temp, ref res);
return res;
}
public static void myfun(int n, int[] rollmax, int[] again, string temp, ref int res)
{
if (n <= 0)
{
res++;
res %= (1000000000 + 7);
return;
}
for (int j = 0; j < 6; j++)
{
if (rollmax[j] <= 0) continue;
string temp1 = temp;
int[] again1;
if (temp1.Length > 0 && temp1[temp1.Length - 1] == Convert.ToChar(j + 49))
{
if (again[j] == 0) continue;
else
{
again1 = (int[])again.Clone();
again1[j]--;
}
}
else
{
again1 = (int[])rollmax.Clone();
again1[j]--;
}
temp1 += (j + 1);
myfun(n - 1, rollmax, again1, temp1, ref res);
}
}
- 递归比较耗时,且消耗内存,虽然可以实现但是效率太低
- 递归,当n>=10时,所消耗的时间大大增加。(动态规划yyds)
- 动态规划,计算时可能出现负数,因为后面的数经过取余1000000007,所以当运算时为负数时,+1000000007即可
- 动态规划,需要减去之前不为 j 的次数,(要点)