Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution:
- def optimalSearchTree(self, A,F, n):
- dp=[[-1]*(1+n) for i in range(n+1)]
- def find(i,j):
- #very important base case
- if i>j:return 0
- if dp[i][j]!=-1:return dp[i][j]
- if j==i:dp[i][j]=F[i]
- else:
- ans=float('inf')
- for k in range(i,j+1):
- left=find(i,k-1)#cost of LBSR
- right=find(k+1,j)#cost of RBST
- 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
- dp[i][j]=ans
- return dp[i][j]
- return find(0,len(A)-1)
Advertisement
Add Comment
Please, Sign In to add comment