0096. Unique Binary Search Trees

96. 不同的二叉搜索树 #

Difficulty: 中等

给定一个整数 n,求以 1 … n 为节点组成的二叉搜索树有多少种?

示例:

输入: 3
输出: 5
解释:
给定 n = 3, 一共有 5 种不同结构的二叉搜索树:

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

题解 #

题解一:DP(动态规划) #

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

复杂度分析

  • 时间复杂度:O(n2)。

  • 空间复杂度:O(n)。

Calendar Dec 9, 2020
Edit Edit this page
本站总访问量:  次 您是本站第  位访问者