[LeetCode] Unique Binary Search Trees n结点二叉搜索树的数目
来源:互联网 发布:做淘宝刷客的被骗经历 编辑:程序博客网 时间:2024/04/27 07:35
声明:原题目转载自LeetCode,解答部分为原创
Problem :
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
Solution:
思路:
想法一:递归求解。首先用数组tree_n[] 记录不同节点数能建立的二叉搜索数的个数。对于n个结点的二叉搜索树,若以顺序第 i 个结点为根,可以创建的二叉搜索树的数量为tree_n[ i - 1 ] * tree_n[ n - i ]。算法缺点是时间复杂度较高。
代码如下:
#include<iostream>#include<vector>using namespace std; class Solution {public: int numTrees(int n) { return root_n(n); } private: int root_n(int n) { if(n == 0 || n == 1) return 1; int num = 0; for(int i = 1 ; i <= n ; i ++) { num += root_n(i - 1) * root_n(n - i);}return num;}};int main(){Solution text;cout << "numTrees(3) : " << text.numTrees(3) << endl;cout << "numTrees(4) : " << text.numTrees(4) << endl;}
想法二:基于想法一的基础上,考虑如何减少调用递归的次数,即每次递归后要记录相关数值,用于下一次递归应用。同时,根据想法一的实现公式的特点,采用线性代数矩阵相乘的方式来实现。
代码如下:
#include<iostream>#include<vector>using namespace std; class Solution {public: int numTrees(int n) { vector<int> tree_n;tree_n.push_back(1);tree_n.push_back(1);for(int i = 2 ; i <= n ; i ++){int num = 0;for(int j = 1 ; j <= i ; j ++){num += tree_n[j - 1] * tree_n[i - j];}tree_n.push_back(num);} return tree_n[n]; }};int main(){Solution text;cout << "numTrees(3) : " << text.numTrees(3) << endl;cout << "numTrees(4) : " << text.numTrees(4) << endl;}
0 0
- [LeetCode] Unique Binary Search Trees n结点二叉搜索树的数目
- LeetCode | Unique Binary Search Trees(二叉搜索树的个数)
- LeetCode OJ 之 Unique Binary Search Trees (不同的二叉搜索树)
- LeetCode OJ 之 Unique Binary Search Trees II (不同的二叉搜索树 - 二)
- [leetcode 96]Unique Binary Search Trees--二叉搜索树的个数问题。
- Leetcode 96 Unique Binary Search Trees(独一的二叉搜索树)
- 动态规划——Unique Binary Search Trees 独一无二的二叉搜索树【LeetCode】
- LeetCode--Unique Binary Search Trees (不同二叉搜索树的个数)Python
- LeetCode 96. Unique Binary Search Trees Python Solution, Catalan数 结点数为n的不同形态的二叉树一共有多少种
- 【LeetCode】Unique Binary Search Trees 二叉查找树的个数
- LeetCode 95. Unique Binary Search Trees II&96. Unique Binary Search Trees--动态规划,二叉树
- LeetCode | Unique Binary Search Trees II(构建二叉搜索树)
- leetCode 95.Unique Binary Search Trees II (唯一二叉搜索树) 解题思路和方法
- leetCode 96.Unique Binary Search Trees (唯一二叉搜索树) 解题思路和方法
- 【LeetCode-面试算法经典-Java实现】【096-Unique Binary Search Trees(唯一二叉搜索树)】
- [LeetCode]Unique Binary Search Trees II生成所有二叉搜索树
- LeetCode 95. Unique Binary Search Trees II(唯一二叉搜索树)
- Leetcode 96. Unique Binary Search Trees 二叉搜索树 解题报告
- caffe入门----pycaffe图片分类
- Ubuntu创建快捷方式具体步骤
- JMS之—— ActiveMQ中使用mysql做持久化报错:Cannot execute statement: impossible to write to binary log since BINL
- 二叉树 C实现
- HDU 4995 暴力
- [LeetCode] Unique Binary Search Trees n结点二叉搜索树的数目
- 单词变换
- C#选择文件、选择文件路径
- Ubuntu创建Android Studio快捷方式
- Oracle PL/SQL编程之五: 异常错误处理(知已知彼、百战不殆)
- nyoj 23 取石子(一)
- 安装操作系统前须知知识(理论)
- Node.js 安装配置
- 最近一个月的面试记录总结