JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

Problem

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

Code

动态规划写法 (视频制作中….)

class Solution {
    public int numTrees(int n) {
        if(n <= 1) return 1;

        int[] dp = new int[n + 1];
        // 没有节点
        dp[0] = 1;
        // 有一个节点
        dp[1] = 1;

        // 从一共有两个节点开始
        for(int i = 2; i <= n; i++){
            // 左子树从0个节点开始
            // 左子树最多也只能是i - 1个节点
            // 因为还有一个节点当根节点
            for(int j = 0; j <= i - 1; j++){
                // 构成左子树的种类 * 构成右子树的种类
                // 注意右子树的节点数量要减去根节点 - 1
                dp[i] += dp[j] * dp[i - j - 1];
            }
        }

        return dp[n];
    }
}

递归写法: 会超时

class Solution {
    public int numTrees(int n) {
        if(n <= 1) return 1;

        int res = 0;
        for(int i = 0; i < n; i++){
            res += numTrees(i) * numTrees(n - 1 - i);
        }

        return res;
    }
}