Number of Distinct Roll Sequences — LeetCode 2318 Python Solution
HardMemoizationDynamic Programming
- Problem
- #2318
- Pattern
- Dynamic Programming
- Reading time
- 4 min
- Source
- leetcode.com
The problem
You are given an integer n. You roll a fair 6-sided dice n times.
Example
- Input
- n = 4
- Output
- 184
- Explanation
- Some of the possible sequences are (1, 2, 3, 4), (6, 1, 2, 3), (1, 2, 3, 1), etc.
Python solution
Python
class Solution:
def distinctSequences(self, n: int) -> int:
if n == 1:
return 6
mod = 10**9 + 7
dp = [[[0] * 6 for _ in range(6)] for _ in range(n + 1)]
for i in range(6):
for j in range(6):
if gcd(i + 1, j + 1) == 1 and i != j:
dp[2][i][j] = 1
for k in range(3, n + 1):
for i in range(6):
for j in range(6):
if gcd(i + 1, j + 1) == 1 and i != j:
for h in range(6):
if gcd(h + 1, i + 1) == 1 and h != i and h != j:
dp[k][i][j] += dp[k - 1][h][i]
ans = 0
for i in range(6):
for j in range(6):
ans += dp[-1][i][j]
return ans % modComplexity
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(n·m) or optimized auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 2318. Number of Distinct Roll Sequences is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming and Memoization.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2318. Number of Distinct Roll Sequences?
- LeetCode 2318. Number of Distinct Roll Sequences is rated Hard on LeetCode.
- What topics does LeetCode 2318. Number of Distinct Roll Sequences cover?
- LeetCode 2318. Number of Distinct Roll Sequences is tagged Memoization and Dynamic Programming on LeetCode.