Similar Problems

Similar Problems not available

Number Of Distinct Roll Sequences - Leetcode Solution

Companies:

LeetCode:  Number Of Distinct Roll Sequences Leetcode Solution

Difficulty: Hard

Topics: dynamic-programming  

The problem "Number of Distinct Roll Sequences" on LeetCode can be solved by using dynamic programming. The problem statement is as follows:

You have a 6-sided dice with faces numbered from 1 to 6, and you roll it repeatedly until you get a certain sequence of numbers. Return the number of distinct sequences that can be obtained by rolling the dice. Two sequences are considered distinct if they have a different number of rolls, or if there exists a position i such that sequences have different numbers at position i.

The approach to solve this problem involves creating a 2D matrix dp of size (n+1) x 6, where n is the length of the desired sequence. dp[i][j] will represent the number of distinct sequences that can be obtained by rolling the dice i times and having the last number rolled be j.

The base case will be that dp[0][0] = 1, which means that when we have not rolled any dice, we have obtained a sequence of length 0 and hence we have 1 distinct sequence.

We can populate the dp matrix using the following recurrence relation:

dp[i][j] = sum(dp[i-1][k]), where k != j and k is a valid face of the dice

This means that the number of distinct sequences that can be obtained by rolling the dice i times and having the last number rolled be j, is equal to the sum of the number of distinct sequences that can be obtained by rolling the dice i-1 times and having the last number rolled be any number except j.

The final answer will be the sum of all elements in the last row of the dp matrix, as this will give us the number of distinct sequences that can be obtained by rolling the dice n times.

The time complexity of this approach is O(n^2), as we need to fill in the entire dp matrix of size (n+1) x 6. The space complexity is also O(n^2), as we are creating a 2D matrix of that size.

Here's the Python code for the dynamic programming approach:

def distinctSequence(n: int) -> int: # Initialize the dp matrix dp = [[0]*6 for _ in range(n+1)] dp[0][0] = 1

# Populate the dp matrix
for i in range(1, n+1):
    for j in range(6):
        for k in range(6):
            if k != j:
                dp[i][j] += dp[i-1][k]

# Return the final answer
return sum(dp[n])

Number Of Distinct Roll Sequences Solution Code

1