HardNo. 2318
Number of Distinct Roll Sequences — LeetCode 2318 Python Solution
- Pattern
- Dynamic Programming
- Topics
- Memoization, 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
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
- Time
- O(n·m) (typical)
- Space · auxiliary
- O(n·m)or optimized
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
| No. | Problem | Difficulty |
|---|---|---|
| 2312 | Selling Pieces of Wood | Hard |
| 2311 | Longest Binary Subsequence Less Than or Equal to K | Medium |
| 2328 | Number of Increasing Paths in a Grid | Hard |
| 0070 | Climbing Stairs | Easy |
| 0241 | Different Ways to Add Parentheses | Medium |
| 0329 | Longest Increasing Path in a Matrix | Hard |
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.