backtracking Flashcards
1
Q
Tribonacci Number
Top Down intuition
A
- Create a hash map
dp
to store the value of computed tribonacci numbers, initialized with the base casesdp[0] = 0
,dp[1] = 1
,dp[2] = 1
. - Let
dfs(i)
be the value of ith
tribonacci numbers:
- If
i
is indp
, returndp[i]
. - Otherwise, recursively solve answer =
dfs(i - 1) + dfs(i - 2) + dfs(i - 3)
and setdp[i] = answer
. Then returnanswer
.
- Return
dfs(n)
.
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)