Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Renat Zamaletdinov
DP + Memo

Renat Zamaletdinov

Mar 25, 2024

It's not required to reconstruct cached data as we only use them either as left or right child without breaking any relationships between parent-to-child nodes.

Should not it be "better" than the provided solution?

#class TreeNode: #  def __init__(self, val): #    self.val = val #    self.left = None #    self.right = None class Solution:   def findUniqueTrees(self, n):     if n == 0:       return []     cache = {}     def dp(start, end):       if start > end:         return [None]       pair = (start, end)       if pair not in cache:         res = []         for i in range(start, end + 1):           left = dp(start, i - 1)           right = dp(i + 1, end)           for l in left:             for r in right:               root = TreeNode(i)               root.left = l               root.right = r               res.append(root)         cache[pair] = res       return cache[pair]     result = dp(1, n)     return result

0

0

Comments
Comments

On this page