Likou brushing notes: 96. Different binary search trees (dynamic programming, detailed diagrams, must be able to understand)

topic:

96. Different binary search trees

Given an integer n, how many kinds of binary search trees are there with 1… n as nodes?

Example:

Input: 3
Output: 5
Explanation:
Given n = 3, there are 5 binary search trees with different structures:
Insert picture description here

Problem solution ideas:

1. Ideas
If k in the integer 1 ~ n is used as the root node value, then 1 ~ k-1 will construct the left subtree, and k+1 ~ n will construct the right subtree.
The form of the left subtree has a species, and the form of the right subtree has b species, so the whole tree has a∗b species.
The number of BST types with k as the root node = the number of BST types in the left subtree * the number of BSTBST types in the right subtree.

The problem becomes: under different kk, the product on the right side of the equal sign is accumulated.

2. Define the DP sub-problem
Insert picture description here
(1) Use 2 and 3 to construct, and use 1, 2 to construct, the number of types is the same, because the number of participants in the construction is the same.
(2) For another example, 2, 3, 4 and 1, 2, 3 are all three consecutive numbers, and the constructed BST has the same number of types, which belongs to the repeated sub-problem.
(3) Definition dp[i]: The number of BST types constructed with the number of consecutive i.

3. State transition equation:

Use i nodes to construct a BST, remove the root node, and construct left and right subtrees with i-1 nodes. The left subtree is allocated 0, and the right subtree is allocated to i−1... and so on.
Insert picture description here
The left subtree uses j, and the right subtree uses ij-1, which can construct dp[j] * dp[ij-1] different kinds of BST.
Insert picture description here
4. Basic conditions
When n = 0, there is no number and only one kind of BST can be formed: empty tree.
When n = 1, there is only one number, and only one kind of BST can be formed: a single node.

Time complexity O(n^2): There are n states to be calculated, and calculating each state requires O(n).

Problem solution python code:

class Solution:
    def numTrees(self, n: int) -> int:
        G = [0]*(n+1)
        G[0], G[1] = 1, 1

        for i in range(2, n+1):
            for j in range(i):
                G[i] += G[j] * G[i-j-1]

        return G[n]

Author: xiao_ben_zhu
link: https://leetcode-cn.com/problems/unique-binary-search-trees/solution/shou-hua-tu-jie-san-chong-xie-fa-dp-di-gui-ji -yi-h/
Source: LeetCode (LeetCode) https://leetcode-cn.com/problems/unique-binary-search-trees/

Guess you like

Origin blog.csdn.net/weixin_44414948/article/details/114671289