96. Unique Binary Search Trees

Q

https://leetcode.com/problems/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.

S

Catalan数

#define MAXSIZE 1000
int numTrees(int n) {
    int res[MAXSIZE];
    int i, j;
    res[0] = 1;
    res[1] = 1;
    for (i = 2; i < MAXSIZE; ++i) {
        res[i] = 0;
    }

    for (i = 2; i <= n; ++i) {
        for (j = 0; j < i; ++j) {
            res[i] += res[j]*res[i-1-j];
        }
    }

    return res[n];
}

你可能感兴趣的:(Leetcode)