backtracking Flashcards

1
Q

Tribonacci Number
Top Down intuition

A
  1. Create a hash map dp to store the value of computed tribonacci numbers, initialized with the base cases dp[0] = 0, dp[1] = 1, dp[2] = 1.
  2. Let dfs(i) be the value of ith
    tribonacci numbers:
  • If i is in dp, return dp[i].
  • Otherwise, recursively solve answer = dfs(i - 1) + dfs(i - 2) + dfs(i - 3) and set dp[i] = answer. Then return answer.
  1. Return dfs(n).
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Tribonnaci Top Down Aproach
Code

A
def tribonacci(n: int) -> int:
    dp = {0: 0, 1: 1, 2: 1}
    def dfs(i):
        if i in dp:
            return dp[i]
        dp[i] = dfs(i - 1) + dfs(i - 2) + dfs(i - 3)
        return dp[i]
    
    return dfs(n)
        
How well did you know this?
1
Not at all
2
3
4
5
Perfectly