当前位置:网站首页>[leetcode] 96 and 95 (how to calculate all legal BST)
[leetcode] 96 and 95 (how to calculate all legal BST)
2022-07-04 12:46:00 【Learn a little every day】
How to calculate all legal BST
I wrote two articles before BST Algorithm related ⽂ Chapter , Chapter one About the middle order traversal pair BST The significance of , Second articles Yes BST Basic operation .
Ben ⽂ Say two questions step by step , Describe how to calculate all legal BST.
96. Different binary search trees

solution : recursive
This is an authentic problem of exhaustion , So what method can correctly enumerate the legal BST How about the number of ?
For interval [1,2,…,n], We calculate each number in turn as the root node , Then sum it up . For example, for n=5, Fixed number 3 As root node , Under this premise, there can be several different BST Well ?
Fix 3 Root node , according to BST characteristic , Its left subtree is a node [1,2] The combination of , The right subtree node is [4,5] The combination of , The product of the combination number of the left subtree and the combination number of the right subtree is 3 As the root node BST Number , be equal to 4.
Abstracted as a recursive process is , For any interval , Calculating the BST Number , Is a pair of BST The sum of the numbers . For any number root node , Its BST The number is , Left interval BST Number ( Combinatorial number ) Multiply by the right interval BST Number ( Combinatorial number ).
There are many repeating subproblems in recursive process , You can use memos ( In the code mamo Array ) To solve .
class Solution:
def numTrees(self, n: int) -> int:
mamo = [[0]*n for _ in range(n)]
# Calculate the closed interval [lo, hi] Composed of BST Number
def count(lo, hi):
nonlocal mamo
if lo >= hi:
return 1
# Check the memo
if mamo[lo][hi] != 0:
return mamo[lo][hi]
res = 0
for i in range(lo, hi+1):
# i As the root node root
left = count(lo, i-1)
right = count(i+1, hi)
# The product of the combination number of left and right subtrees is BST Total of
res += left*right
# Store memos
mamo[lo][hi] = res
return res
# Calculate the closed interval [1, n] Composed of BST Number
return count(0, n-1)
95. Different binary search trees 2

solution : recursive
Consistent with the above question , The original problem is decomposed into subproblems with left and right intervals , Recursively solve the original problem according to the return result of the subproblem . The specific steps are as follows :
- For a given interval , Exhausting root All possible nodes .
- Recursively construct all the legal properties of the left and right subtrees BST.
- to root The node enumerates the combination of all left and right subtrees . Return as result .
class Solution:
def generateTrees(self, n: int) -> List[TreeNode]:
# Memo operation
mamo = [[None]*(n+1) for _ in range(n+1)]
# Tectonic closed interval [lo, hi] Composed of BST
def count(lo, hi):
if lo > hi:
return [None]
if lo == hi:
return [TreeNode(lo)]
if mamo[lo][hi]:
return mamo[lo][hi]
result = []
# 1、 Exhausting root All possible nodes
for i in range(lo, hi+1):
# 2、 Recursively construct all the legal properties of the left and right subtrees BST.
l_result = count(lo, i-1)
r_result = count(i+1, hi)
# 3、 to root The node enumerates the combination of all left and right subtrees .
for left in l_result:
for right in r_result:
# i As root node root Value
root = TreeNode(i)
root.left = left
root.right = right
result.append(root)
mamo[lo][hi] = result
return result
return count(1, n)
边栏推荐
- Haproxy cluster
- BCD code Baidu Encyclopedia
- The most robust financial products in 2022
- The frost peel off the purple dragon scale, and the xiariba people will talk about database SQL optimization and the principle of indexing (primary / secondary / clustered / non clustered)
- Jetson TX2 configures common libraries such as tensorflow and pytoch
- Clion configuration of opencv
- DVWA range exercise 4
- 01. Basics - MySQL overview
- DC-5 target
- Transformer principle and code elaboration (pytorch)
猜你喜欢

Ml and NLP are still developing rapidly in 2021. Deepmind scientists recently summarized 15 bright research directions in the past year. Come and see which direction is suitable for your new pit
![[the way of programmer training] - 2 Perfect number calculation](/img/fd/4bb8560f601daddaa8895f20215be4.jpg)
[the way of programmer training] - 2 Perfect number calculation

Will the concept of "being integrated" become a new inflection point of the information and innovation industry?

01. Basics - MySQL overview
![[notes] in depth explanation of assets, resources and assetbundles](/img/e9/ae401b45743ea65986ae01b54e3593.jpg)
[notes] in depth explanation of assets, resources and assetbundles

Practice of retro SOAP Protocol

Tableau makes data summary after linking the database, and summary exceptions occasionally occur.

MySQL advanced review

The database connection code determines whether the account password is correct, but the correct account password always jumps to the failure page with wrong account password
![[data clustering] section 3 of Chapter 4: DBSCAN performance analysis, advantages and disadvantages, and parameter selection methods](/img/e6/2b46d72049ea50f89d0234eab88439.png)
[data clustering] section 3 of Chapter 4: DBSCAN performance analysis, advantages and disadvantages, and parameter selection methods
随机推荐
Global and Chinese markets of digital PCR and real-time PCR 2022-2028: Research Report on technology, participants, trends, market size and share
nn. Exploration and experiment of batchnorm2d principle
How to use the mongodb ID array to get multiple documents- How to get multiple document using array of MongoDb id?
Leetcode day 17
Langue C: trouver le nombre de palindromes dont 100 - 999 est un multiple de 7
C语言:求字符串的长度
Global and Chinese markets for environmental disinfection robots 2022-2028: Research Report on technology, participants, trends, market size and share
C language array
Bottom Logic -- Mind Map
Lecture 9
Entity framework calls Max on null on records - Entity Framework calling Max on null on records
Is the main thread the same as the UI thread- Is main thread the same as UI thread?
C language: the sorting problem of circle number reporting
'using an alias column in the where clause in PostgreSQL' - using an alias column in the where clause in PostgreSQL
Interview question MySQL transaction (TCL) isolation (four characteristics)
Global and Chinese market for naval vessel maintenance 2022-2028: Research Report on technology, participants, trends, market size and share
Lvs+kept highly available cluster
Transformer principle and code elaboration (pytorch)
Anti clockwise rotation method of event arrangement -- PHP implementation
16.内存使用与分段