96. Different Binary Search Trees

Topic source: 96. Different binary search trees
Given an integer n, how many kinds of binary search trees are there with exactly n nodes and the node values ​​from 1 to n are different from each other? Returns the number of binary search trees that satisfy the meaning of the question.
insert image description here
Idea:
Given an ordered sequence 1:n in dynamic programming, when searching for the number of subtrees, it is assumed that the number of binary search trees with i as the root is f(i); given n nodes can form a binary tree The number of searches is G(n); then
G(n)=f(0)+f(1)+f(2)+…+f(n)
respectively represent [with the first node as the root node : The first 0 nodes are on the left, and the last n-1 nodes are on the right to calculate the number of subtrees; take the second node as the root node: the first 1 node is on the left, and the last n-2 nodes Calculate the number of subtrees on the right; take the third node as the root node: the first 2 nodes are on the left, and the last n-3 nodes are on the right to calculate the number of subtrees; ...; Take the nth node For the root node: the first n-1 nodes are on the left, and the last 0 nodes are on the right to calculate the number of subtrees] a total of n+1 cases.
Further, let's discuss the computation of f(i). f(i) represents the number of subtrees with the first i-1 nodes on the left and the last ni nodes on the right. The number of search trees with the first i-1 nodes on the left is: G(i-1), and the number of search trees with the last ni nodes is G(ni), then:
f(i)=G( i-1)*G(ni)
Finally, substitute the formula of f(i), that is, to obtain the expression of G(n):
G(n)=G(0)*G(n-1)+G(1 )*G(n-1)+…+G(n)*G(0)
The final code is as follows:

class Solution(object):
    def numTrees(self, n):
        """
        :type n: int
        :rtype: int
        """
        f = [0 for _ in range(n+1)]
        f[1] = 1
        f[0] = 1
        for i in range(2,n+1):
        	for j in range(i+1):
        		f[i] += f[i-1]*f[i-j]
        return f[-1]

The code runs as follows:
insert image description here
Another solution is as follows:

class Solution(object):
    def numTrees(self, n):
        """
        :type n: int
        :rtype: int
        """
        f = [0 for _ in range(n+1)]
        f[1] = 1
        f[0] = 1
        for j in range(2, n+1):
            for i in range(0, n):
                f[j] += f[i]*f[j-i-1]
        return f[-1]

The results of the operation are as follows:
insert image description here
It can be seen that the two methods are similar, but the space and time are completely opposite, and the difference between the two has not yet been understood. Those who have an understanding can discuss it together~
Method 1 reference link
Method 2 Reference link

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324339754&siteId=291194637