Iam_Sandeep

Optimal Binary Search Tree DP cost

Apr 27th, 2022
1,434
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.69 KB | None | 0 0
  1.  
  2. class Solution:
  3.     def optimalSearchTree(self, A,F, n):
  4.         dp=[[-1]*(1+n) for i in range(n+1)]
  5.         def find(i,j):
  6.             #very important base case
  7.             if i>j:return 0
  8.             if dp[i][j]!=-1:return dp[i][j]
  9.             if j==i:dp[i][j]=F[i]
  10.             else:
  11.                 ans=float('inf')
  12.                 for k in range(i,j+1):
  13.                     left=find(i,k-1)#cost of LBSR
  14.                     right=find(k+1,j)#cost of RBST
  15.                     ans=min(ans,sum(F[i:j+1])+left+right)# additionally we add each node cost in range(i,j+1) to compensate extra height gained
  16.                 dp[i][j]=ans
  17.             return dp[i][j]
  18.         return find(0,len(A)-1)
Advertisement
Add Comment
Please, Sign In to add comment