LeetCode 96:Unique Binary Search Trees

题意描述

给定整数n,有多少个结构唯一的BST(二叉搜索树)?

测试用例

Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

解题思路

一、思路一

  • 根据上图可以发现,当根节点的左子树有i个节点时,右子树有(n-i-1)个节点。
  • 左子树与右子树的取值范围都是【0,n-1】

可以得出如下的转义方程

根据方程写出程序,如下:

    public int numTrees(int n) {
            if(n < 1) return 0;
            int[] nums = new int[n+1];
            nums[0] = 1;//没有节点,一种情况
            nums[1] = 1;//只有一个节点,一种情况
            for(int i=2;i<=n;i++){	//从两个节点开始
                for(int j=0;j<i;j++){	//左子树的节点树从0开始计算
                    nums[i] += (nums[i-j-1] * nums[j]);
                }
            }
            return nums[n];
        }

猜你喜欢

转载自www.cnblogs.com/le-le/p/12938970.html
今日推荐