【Leetcode】96. 不同的二叉搜索树
2019-03-11 19:10
225 查看
QUESTION
medium
题目描述
给定一个整数
n,求以
1 ... n为节点组成的二叉搜索树有多少种?
示例:
输入: 3 输出: 5 解释: 给定 n = 3, 一共有 5 种不同结构的二叉搜索树: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
说明
注意是
BST哦
SOLUTION
首先上来应该思考二叉搜索树的性质,左子树节点值小于根,右子树相反,那么有(注意了,下面的
左(0)表示,左子树包含0个节点)
- n = 1, 1 种
- n = 2, 2 种,左(0)*右(1),左(1)*右(0)
- n = 3, 5 种,左(0)*右(2),左(1)*右(1),左(2)*右(0)
- n = n, x 种,x = dp[0]*dp[n-1] + dp[1]*dp[n-2] + … + dp[n-1]*dp[0]
原来是个动态规划问题
方法一
直接两层循环一直求到
dp
int numTrees(int n) { if(n <= 1) return n; //n = 0, 1的情况直接返回就可以了 int *dp = new int[n + 1]; dp[0] = 1; //这里不能设0,要设1 dp[1] = 1; for(int l = 2; l <= n; l++){ dp[l] = 0; for(int i = 0; i < l; i++){ dp[l] += dp[i] * dp[l-i-1]; } } int res = dp[n]; delete []dp; //释放内存是好习惯 return res; }
相关文章推荐
- LeetCode 96 Unique Binary Search Trees不同的二叉搜索树的个数
- 95. 不同的二叉搜索树 II(来源LeetCode)
- LeetCode--Unique Binary Search Trees (不同二叉搜索树的个数)Python
- leetcode 95. 不同的二叉搜索树 II
- 【LeetCode】二叉搜索树的前序,中序,后续遍历非递归方法
- 96. 不同的二叉搜索树
- [LeetCode] 108. Convert Sorted Array to Binary Search Tree 把有序数组转成二叉搜索树
- [leetcode] 230. Kth Smallest Element in a BST 找出二叉搜索树中的第k小的元素
- LeetCode-99.恢复二叉搜索树(相关话题:深度优先搜索)
- [leetcode 230]Kth Smallest Element in a BST----求二叉搜索树的第K小值
- [LeetCode] Convert Sorted Array to Binary Search Tree 将有序数组转为二叉搜索树
- [LeetCode] 270. Closest Binary Search Tree Value 最近的二叉搜索树的值
- LeetCode—判断是否为二叉搜索树
- [LeetCode] Count Numbers with Unique Digits 计算各位数值不同的数的个数
- leetcode_230. Kth Smallest Element in a BST 求二叉搜索树中的第k小的元素,中序遍历法
- LeetCode 538. Convert BST to Greater Tree (把二叉搜索树转换成较大树)
- LeetCode(98)验证二叉搜索树(102,107)层次遍历
- 不同路径(LeetCode)
- leetcode 669二叉搜索树
- leetcode 验证二叉搜索树