Unique Binary Search Trees

Given n, how many structurally unique BST’s (binary search trees) that store values 1…n?

For example,
Given n = 3, there are a total of 5 unique BST’s.

1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3

题目解析:找到节点数为n,节点的值为1….n,的所有二叉查找树的数目。
思路:用res[i]表示节点数为i的二叉查找树的数目,下面分别计算根节点为1-n的情况,假设根节点为j,那么其二叉搜索树的数目为res[j-1]* res[n-1-j],即其左子树(所有值比j小)的数目乘以其右子树(值比j大)的数目,而其左子树又是一个二叉搜索树,且节点数为j-1,也就是res[j-1],右子树同样也是二叉搜索树,数目为n-j,即res[n-1-j],而根节点值的取值范围为1…n,那么就有如下的递推关系:
res[0] = 1
res[i] = sum(res[j]*res[i-j])j=1…i
其实这也是卡特兰数的定义。
代码如下:

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

你可能感兴趣的:(leetcode)