Skip to content

Latest commit

 

History

History
55 lines (40 loc) · 1.36 KB

96-unique-binary-search-trees.md

File metadata and controls

55 lines (40 loc) · 1.36 KB

96. Unique Binary Search Trees - 不同的二叉搜索树

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

示例:

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

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

题目标签:Tree / Dynamic Programming

题目链接:LeetCode / LeetCode中国

题解

Language Runtime Memory
cpp 0 ms 831.5 KB
class Solution {
public:
    int numTrees(int n) {
        /*
          x    0  1  2  3  4
        F(x)   1  1  2  5  14
        3 : 0,2  1,1  2,0
        5 = 1*2 + 1*1 + 2*1
        */
        int dp[n+1] {1};
        for (int x=1; x<=n; ++x) {
            for (int i=0; i<x; ++i) {
                dp[x] += dp[i] * dp[x - 1 - i];
            }
        }
        return dp[n];
    }
};