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,如需转载请自行联系原作者

相关文章
|
6月前
|
算法 索引
Binary Search
Binary Search “【5月更文挑战第21天】”
49 5
|
6月前
C. Binary Search
C. Binary Search
|
机器学习/深度学习
Leetcode-Medium 96.Unique Binary Search Trees
Leetcode-Medium 96.Unique Binary Search Trees
97 0
|
算法 Python
Leetcode-Medium 98. Validate Binary Search Tree
Leetcode-Medium 98. Validate Binary Search Tree
127 0
|
机器学习/深度学习
1064. Complete Binary Search Tree (30)
#include #include #include using namespace std; const int maxn = 1001; vector num(maxn), cbt(maxn); int n, c...
847 0
|
算法 索引 C++
|
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.
1183 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.
902 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.
807 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 \
952 0