LeetCode: 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.

卡特兰数。

class Solution {
public:
    int numTrees(int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (n == 0) return 1;
        int sum = 0;
        for (int i = 0; i < n; ++i)
        {
            sum += numTrees(i) * numTrees(n-1-i);
        }
        return sum;
    }
};


你可能感兴趣的:(LeetCode: Unique Binary Search Trees)