Unique Binary Search Trees

简介:

分析

根结点固定时平衡二叉树个数=左孩子的个数 * 右孩子的个数。又左孩子或右孩子为空是不妨置为1,这样

0个结点时,f(0) = 1

1个结点时,f(1) = f(0) * f(0) = 1

2个结点时,f(2) = f(0) * f(1) + f(1) * f(0)

3个结点时,f(3) = f(0) * f(2) + f(1) * f(1) + f(2) * f(0)

规律

n个结点时: f(n) = f(0) * f(n-1) + f(1) * f(n-2) + ... *f(n-1) * f(1)

为了记忆原来的值,用容器(数组)存一下。

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class  Solution {
public :
     int  numTrees( int  n) {
         if (n <= 0)
             return  0;
         vector< int > vec;
         vec.push_back(1);
         vec.push_back(1);
         for ( int  i = 2; i <= n; ++i)
         {
             int  tmp = 0;
             for ( int  j = 0; j < i; ++j)
                 tmp += vec[j] * vec[i - 1 - j];
             vec.push_back(tmp);
         }
         return  vec[n];
     }
};

  





本文转自jihite博客园博客,原文链接:http://www.cnblogs.com/kaituorensheng/p/3652976.html,如需转载请自行联系原作者

相关文章
|
机器学习/深度学习
Leetcode-Medium 96.Unique Binary Search Trees
Leetcode-Medium 96.Unique Binary Search Trees
102 0
|
C++
[LeetCode] Closest Binary Search Tree Value II
Problem Description: Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target.
1190 0
|
C++
[LeetCode] Closest Binary Search Tree Value
Problem Description: Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
906 0
[LeetCode] Lowest Common Ancestor of a Binary Search Tree
Well, remember to take advantage of the property of binary search trees, which is, node -> left -> val < node -> val < node -> right -> val.
809 0
【LeetCode从零单排】No96 Unique Binary Search Trees
题目 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 \
957 0