Skip to content

Latest commit

 

History

History
57 lines (51 loc) · 1.46 KB

1223.掷骰子模拟.md

File metadata and controls

57 lines (51 loc) · 1.46 KB

1223.掷骰子模拟

/*
 * @lc app=leetcode.cn id=1223 lang=typescript
 *
 * [1223] 掷骰子模拟
 */

// @lc code=start
function dieSimulator(n: number, rollMax: number[]): number {}
// @lc code=end

解法 1: 动态规划

function dieSimulator(n: number, rollMax: number[]): number {
  const MOD = 10 ** 9 + 7
  const dp: number[][][] = Array.from({ length: n + 1 }, () => Array.from({ length: 7 }, () => new Array(16).fill(0)))
  for (let i = 1; i <= 6; i++) dp[1][i][1] = 1
  for (let i = 1; i <= n; i++) {
    for (let j = 1; j <= 6; j++) {
      for (let k = rollMax[j - 1]; k > 1; k--) {
        dp[i][j][k] = dp[i - 1][j][k - 1]
      }
      for (let k = 1; k <= 6; k++) {
        if (k === j) continue
        for (let l = 1; l < 16; l++) {
          if (!dp[i - 1][k][l]) break
          dp[i][j][1] = (dp[i][j][1] + dp[i - 1][k][l]) % MOD
        }
      }
    }
  }
  let res = 0
  for (let i = 1; i <= 6; i++) {
    for (let j = 1; j < 16; j++) {
      res = (res + dp[n][i][j]) % MOD
    }
  }
  return res
}

Case

test.each([
  { input: { n: 4, rollMax: [2, 1, 1, 3, 3, 2] }, output: 1082 },
  { input: { n: 2, rollMax: [1, 1, 2, 2, 2, 3] }, output: 34 },
  { input: { n: 2, rollMax: [1, 1, 1, 1, 1, 1] }, output: 30 },
  { input: { n: 3, rollMax: [1, 1, 1, 2, 2, 3] }, output: 181 },
])('input: n = $input.n, rollMax = $input.rollMax', ({ input: { n, rollMax }, output }) => {
  expect(dieSimulator(n, rollMax)).toEqual(output)
})