欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

96. Unique Binary Search Trees

程序员文章站 2022-07-15 11:03:22
...

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
int numTrees(int n) {
    if (n <= 0) {
        return 0;
    }
    // 用于计数
    int counts[n + 1];
    counts[0] = 1;
    counts[1] = 1;
    
    
    int inds;
    int partition;
    int tmp_count;
    for (inds = 2; inds <= n; ++inds) {
        tmp_count = 0;
        for(partition = 1; partition <= inds; ++partition) {
            tmp_count += counts[partition - 1] * counts[inds - partition];
        }
        counts[inds] = tmp_count;
    }
    return counts[n];
}
思想:

96. Unique Binary Search Trees