leetcode96

Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Example:
Input: 3
Output: 5
Explanation:
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

DP。
这种只求个数字或者求boolean的很多都是DP。
定义: dp[i]表示数字1…n一共有多少种BST结构。
状态转移方程:dp[i] = dp[j]*dp[i - 1 - j] 对所有满足 0<=j<=i-1 的 j 求和。
初始化:dp[0] = 1;
返回值:dp[n];

状态转移解释:关键在于连续数字组合上BST的一个性质:根节点的值确定的时候,左右各放多少数也会确定。general case的时候,比如4,那你根节点可以分为放1234的四种情况。放1,左必0右必3;放2,左必1右必2;放3,左2右1;放4,左3右0。左右又是连着的数组,它们的结构又可以dp索引下去。

实现:

class Solution {
    public int numTrees(int n) {
        int[] dp = new int[n + 1];
        dp[0] = 1;
        for (int i = 1; i < dp.length; i++) {
            for (int j = 0; j < i; j++) {
                dp[i] += dp[j] * dp[i - 1 - j];
            }
        }
        return dp[n];
    }
}
原文地址:https://www.cnblogs.com/jasminemzy/p/9666850.html