【一天一道LeetCode】#96. Unique Binary Search Trees

一天一道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github
欢迎大家关注我的新浪微博,我的新浪微博
欢迎转载,转载请注明出处

(一)题目

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.
这里写图片描述

(二)解题

题目大意:给定一个数n,找出1~n组成的二叉搜索树的个数!

可以参考【一天一道LeetCode】#95. Unique Binary Search Trees II

如果单单求个数的话,可以简化。
n=1时,num=1;n=2时,num=2;n=3时,num=5!
可以找出规律,num[i] = num[left]*num[right]!i从1取到n,就为num[n]的值。left和right为左右的节点个数。(节点个数小于等于1的时候记二叉搜索树个数为1)
以题目中的例子为例,取1为根节点,2,3组成的二叉搜索树个数为2(right),左边为1,所以1为根节点的二叉搜索树个数为2,依次可以算出,2为根节点时个数为1,3为根节点的个数为2,加起来为5!

class Solution {
public:
    int numTrees(int n) {
        vector<int> num(n+1,-1);//存放i个节点存放的二叉搜索树个数
        int ret = calNumTrees(1,n,num);
        return ret;
    }
    int calNumTrees(int start , int end , vector<int>& num)
    {
        if(num[end - start +1] != -1) return num[end - start +1];
        if(start >= end) return 1;//当少于等于1个节点时,二叉搜索树个数记为1
        int temp = 0;
        for(int i = start ; i <= end ; i++)//依次以1到n为根节点
        {
            int left = calNumTrees(start,i-1,num);//左边二叉搜索树的个数
            int right = calNumTrees(i+1,end,num);//右边二叉搜索树的个数
            temp +=(left*right);
        }
        if(num[end - start +1] == -1) num[end-start+1] = temp;//num[i]存放1~i组成的个数
        return temp;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值