1223. 掷骰子模拟 _动态规划与递归

有一个骰子模拟器会每次投掷的时候生成一个 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);
			}
		}
  1. 递归比较耗时,且消耗内存,虽然可以实现但是效率太低
  2. 递归,当n>=10时,所消耗的时间大大增加。(动态规划yyds)
  3. 动态规划,计算时可能出现负数,因为后面的数经过取余1000000007,所以当运算时为负数时,+1000000007即可
  4. 动态规划,需要减去之前不为 j 的次数,(要点)
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值