【leetcode】96. Unique Binary Search Trees

1. 题目

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

2. 思路

同上一次的递推思路。
f(n) = sum { f(i) * f(n-1-i) } , i=0->n-1。

n=0的情况,本应该特殊处理为0,这里的ac答案却要求是1.

3. 代码

class Solution {
public:
    int numTrees(int n) {
        int num[n];
        num[0] = 1; num[1] = 1;
        for (int i = 2; i <= n; i++) {
            num[i] = 0;
            for (int j = 0; j < i; j++) {
                num[i] += num[j] * num[i-j-1];
            }
        }
        return num[n];
    }
};
    原文作者:knzeus
    原文地址: https://segmentfault.com/a/1190000007444730
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞