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;    }}}*/


原创粉丝点击