96. Unique Binary Search Trees

来源:互联网 发布:淘宝上首页多少钱 编辑:程序博客网 时间:2024/06/07 02:39

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];}
思想: