FTPrep, 96 Unique Binary Search Trees
来源:互联网 发布:python 可变参数 编辑:程序博客网 时间:2024/05/20 21:22
这道题拿到手有点不知道怎么开始。
看了别人的分析,自己画一画 几种情况,其实也就明白了。
代码里的变量名说明了思路, 就是用DP的方法,记录 当node总数为n时,符合条件的数的情况。然后不断可以根据之前所有的 1 to (n-1) 的情况,来得到 n 的情况。
代码如下:
class Solution { public int numTrees(int n) { if(n==0 || n==1) return n; int[] record = new int[n+1]; // index i means the total number of the TreeNode record[0]=1; record[1]=1; // the set up of record[0] and record[1] are in accordance to the special case, thus can be combined actually. for(int totalNumOfTreeNode=2; totalNumOfTreeNode<=n; totalNumOfTreeNode++){ for(int numOfTreeNodeOnLeft=0; numOfTreeNodeOnLeft<totalNumOfTreeNode; numOfTreeNodeOnLeft++){ // numOfTreeNodeOnLeft means the number of TreeNode on the left side of root. record[totalNumOfTreeNode] += record[numOfTreeNodeOnLeft]*record[totalNumOfTreeNode-1-numOfTreeNodeOnLeft]; // numOfTreeNode-1 means 1 node was picked, so need to -1 } } return record[n]; // n means total# of TreeNode is n; }}// 有一点要注意,对于理解题意:就是在选定左右节点个数的时候,其实就选定了哪个节点作为root节点,所以在root的选择上是没有变化的就是1种。record[i]所代表的就是以 一个且只有一个root节点的所有树的情况。/*class Solution { public int numTrees(int n) { if(n==0 || n==1) return n; int[] record = new int[n+1]; // index n means the total number of the TreeNode record[0]=1; record[1]=1; // the set up of record[0] and record[1] are in accordance to the special case, thus can be combined actually. for(int i=2; i<=n; i++){ for(int j=0; j<i; j++){ // j means the number of TreeNode on the left side of root. record[i] += record[j]*record[i-1-j]; // i-1 means 1 node was picked, so need to -1 } } return record[n]; // n means total# of TreeNode is n; }}}*/
阅读全文
0 0
- FTPrep, 96 Unique Binary Search Trees
- 96Unique Binary Search Trees
- [96]Unique Binary Search Trees
- 96Unique Binary Search Trees
- 96 - Unique Binary Search Trees
- 96 . Unique Binary Search Trees
- 96 Unique Binary Search Trees
- 96-Unique Binary Search Trees
- 96-Unique Binary Search Trees
- Unique Binary Search Trees
- Unique Binary Search Trees
- Unique Binary Search Trees
- Unique Binary Search Trees
- Unique Binary Search Trees
- Unique Binary Search Trees
- Unique Binary Search Trees
- Unique Binary Search Trees
- Unique Binary Search Trees
- sequential container overview(C++ 容器简介)
- 【Leetcode】【python】Permutations II
- 【Leetcode】【python】Rotate Image
- FTPrep, 95 Unique Binary Search Trees II, TODO: a little confused
- Java基础语法
- FTPrep, 96 Unique Binary Search Trees
- TWO
- 欢迎使用CSDN-markdown编辑器
- 死亡
- 面向对象
- 第二章 SQL命令参考-ALTER CONVERSION
- checkbox 表示
- チェックボックス表示
- ESLint 的正式使用感受