当前位置:首页 > 编程笔记 > 正文
已解决

力扣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%的人还看了

猜你感兴趣

版权申明

本文"力扣labuladong——一刷day38":http://eshow365.cn/6-39483-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!