Reflections different binary search tree unique-binary-search-trees of

Title: Given an integer the n- , seeking to ... 1  the n-  node binary search tree composed of how many?

It is easy to spot patterns:

For the binary tree of n nodes, the root node if it is k, the left subtree binary 1 ... k-1, and the right subtree of k + 1 ... n binary tree.

and soG(n)= \sum_{i=0}^{n-1}G(i)G(n-1-i)

Mathematical structure has been very clear, the next C ++ implementation with the following:

class Solution {
public:
    int arr[1000]={1,1,2};
    int numTrees(int n) {
        if(arr[n]!=0) return arr[n];
        int sum=0;
        for(int i=0;i<n;++i){
            sum+=numTrees(i)*numTrees(n-1-i);
        }
        arr[n]=sum;
        return sum;
    }
};

It is natural to use the memorandum of recursion, but the essence of chicken dishes play, re-examine the code, find recursion and useless as:

For n> numTrees (n) 2, obviously it requires recursive calls numTrees (n-1), which in turn calls numTrees (n-2) ...... until numTrees (2).

Completely from arr [3] to count iterations arr [n].

Vegetable dish, and this as a warning.

Guess you like

Origin blog.csdn.net/Chenyun__/article/details/89299952