Leetcode 96. Different binary search tree problem-solving ideas and implemented in C ++

Problem-solving ideas:

Because the left and right sub-tree binary search trees are binary search tree. The total number of input integer n, find all its binary search tree, the root node is seeking respectively 1,2, ..., n the sum of the binary search tree.

Assuming that the total number of binary search tree i is f (i), when the root node is j, the total number of the other binary search tree left subtree multiplied by the total number of the total number of trees for the right child, that f (j - 1) * f (n - j).

So long as we record an array nums it.

 

class Solution {
public:
    int numTrees(int n) {
        vector<int> nums(n+1, 0);
        nums[0] = 1;
        nums[1] = 1;
        for(int i = 2; i <= n; i++){
            for(int j = 1; j <= i; j++){
                nums[i] = nums[i] + nums[j - 1] * nums[i - j];
            }
        }
        return nums[n];
    }
};

 

 

Guess you like

Origin blog.csdn.net/gjh13/article/details/92103301