96. Unique Binary Search Trees

来源:互联网 发布:ubuntu设置用户根目录 编辑:程序博客网 时间:2024/06/08 02:09

题目:

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
题解:

一组单调递增的值,能构成多少棵结构上独一无二的二叉搜索树,只和这组值的个数有关,和值无关。

根据原题得

状态转移方程:

g(n) = g(0)*g(n-1) + g(1) * g(n-2) + g(2) * g(n-3) + ......+g(n-1) * g(0).

具体代码如下:

class Solution {public:    int numTrees(int n) {        int * g = new int[n+1];        g[0] = g[1] = 1;        for(int i = 2; i <= n; i++) {            g[i] = 0;            for(int j = 1; j <= i; j++) {                g[i] += (g[j-1] * g[i-j]);            }        }        return g[n];    }};
end!

原创粉丝点击