[Leetcode] Unique Binary Search Trees

来源:互联网 发布:沙发品牌推荐 知乎 编辑:程序博客网 时间:2024/05/16 14:40

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

public class Solution {    public int numTrees(int n) {        if(n <= 1) {            return 1;        }        int[] cache = new int[n+1];        cache[0] = 1;        cache[1] = 1;        for(int j = 2; j <= n; j++) {            for(int i = 0; i < j; i++) {                cache[j] += cache[i]*cache[j-1-i];            }        }        return cache[n];    }}


0 0