码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode OJ 96. Unique Binary Search Trees

时间:2018-04-21 00:23:50      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:两种   class   NPU   ...   public   tco   any   ret   arch   

题目

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

解答

都怪娃没有催我更博。。。略略略

树就是递归定义的,自然想到递归的方法,确定一个根节点i,由于BST的性质,左右两边的节点数可以确定,那么就可以用同样的函数去求左右子树的种类数量,相乘就是以i为根节点的BST的种类数量,递归返回的条件是0个节点或1个节点时,这两种情况下BST的种类数量都是1。

当然直接这么做会超时,毕竟k个节点的左子树和n - k - 1个节点的右子树,n - k - 1个节点的左子树和k个节点的右子树得出的结果是一样的,所以算一遍就好了。。。

下面是AC的代码:

class Solution {
public:
    int numTrees(int n) {
        if(n == 0){
            return 1;
        }
        if(n == 1){
            return 1;
        }
        int sum = 0;
        for(int i = 1; i <= n / 2; i++){
            sum += numTrees(i - 1) * numTrees(n - i);
        }
        sum *= 2;
        if(n % 2 == 1){
            sum += numTrees(n / 2 + 1 - 1) * numTrees(n - n / 2 - 1);
        }
        return sum;
    }
};

120

LeetCode OJ 96. Unique Binary Search Trees

标签:两种   class   NPU   ...   public   tco   any   ret   arch   

原文地址:https://www.cnblogs.com/YuNanlong/p/8894232.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!