第十一周

96. Unique Binary Search Trees

  • Total Accepted: 116783
  • Total Submissions: 288808
  • Difficulty: Medium
  • Contributor: LeetCode

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

Subscribe to see which companies asked this question.

Show Tags
Show Similar Problems

思路:
假设二叉树的总数为f(n),考虑f(n)和f(n-1)的关系,因为n为最大数,所以它可以成为f(n-1)的最右的一片叶子,也可以作为根。另外,如果把n插入f(n-1)的二叉树中间,若在n的上面有i个元素,则有f(i)种可能,而在下 面则有(n-1-i)个元素,有f(n-1-i)种可能。故f(n) = f(n-1) * 2 + f(i) * f(n-1-i) + .....,其中i从1到n-2。
代码:
class Solution {
public:
    int numTrees(int n) {
        if(n == 1) return 1;
        else if(n == 2) return 2;
        else{
            int k = 0;
            for(int i = 1; i < n - 1; i ++){
                k = k + numTrees(i) * numTrees(n - 1 - i);
            }
            return numTrees(n - 1) * 2 + k;
        }
    }
    
    
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值