已解决
力扣labuladong——一刷day38
来自网友在路上 173873提问 提问时间:2023-11-19 17:30:05阅读次数: 73
最佳答案 问答题库738位专家为你答疑解惑
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
- 前言
- 一、力扣96. 不同的二叉搜索树
- 二、力扣95. 不同的二叉搜索树 II
前言
计算n个节点的BSF数量,与构造n个节点的BFS的全收集
一、力扣96. 不同的二叉搜索树
class Solution {public int numTrees(int n) {int[] dp = new int[n+1];dp[0] = 1;dp[1] = 1;for(int i = 2; i <= n; i ++){for(int j = 1; j <= i; j ++){dp[i] += dp[j-1] * dp[i-j];}}return dp[n];}
}
回溯
class Solution {int[][] memo;public int numTrees(int n) {memo = new int[n+1][n+1];return fun(1,n);}public int fun(int low, int high){if(low > high){return 1;}if(memo[low][high] != 0){return memo[low][high];}int res = 0;for(int i = low; i <= high; i ++){res += fun(low, i-1) * fun(i+1,high);}memo[low][high] = res;return res;}
}
二、力扣95. 不同的二叉搜索树 II
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {public List<TreeNode> generateTrees(int n) {List<TreeNode> res = new LinkedList<>();if(n == 0){return res;}return fun(1,n);}public List<TreeNode> fun(int low, int high){List<TreeNode> res = new LinkedList<>();if(low > high){res.add(null);return res;}for(int i = low; i <= high; i ++){List<TreeNode> l = fun(low,i-1);List<TreeNode> r = fun(i+1,high);for(TreeNode tl : l){for(TreeNode tr : r){TreeNode cur = new TreeNode(i);cur.left = tl;cur.right = tr;res.add(cur);}}}return res;}
}
查看全文
99%的人还看了
相似问题
- 〖大前端 - 基础入门三大核心之JS篇㊲〗- DOM改变元素节点的css样式、HTML属性
- Java 算法篇-链表的经典算法:判断回文链表、判断环链表与寻找环入口节点(“龟兔赛跑“算法实现)
- 代码随想录二刷 | 链表 | 删除链表的倒数第N个节点
- 节点导纳矩阵
- bhosts 显示节点 “unreach“ 状态
- 电子电器架构 —— 车载网关边缘节点总线转换
- 〖大前端 - 基础入门三大核心之JS篇㊳〗- DOM访问元素节点
- 第四天||24. 两两交换链表中的节点 ● 19.删除链表的倒数第N个节点 ● 面试题 02.07. 链表相交 ● 142.环形链表II
- CS224W5.1——消息传递和节点分类
- Vue报错解决Error in v-on handler: “Error: 无效的节点选择器:#div1“
猜你感兴趣
版权申明
本文"力扣labuladong——一刷day38":http://eshow365.cn/6-39483-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!