LeetCode 96. Unique Binary Search Trees(动态规划)

题目来源:https://leetcode.com/problems/unique-binary-search-trees/

问题描述

96. Unique Binary Search Trees

Medium

Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?

Example:

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

------------------------------------------------------------

题意

给定整数n,求所有n个节点的二叉搜索树的数量(给定二叉搜索树的顺序为“左子树<根节点<右子树”)

------------------------------------------------------------

思路

动态规划。动态规划数组的dp[i]表示i个节点的二叉搜索树的个数。考虑n个节点的情形,其中必有一个为根节点,剩下n-1个节点可以有0/1/2/…/n-1位于左子树,n-1/n-2/n-3/…/0个位于右子树,因此状态转移方程为:

dp[n] = dp[0]*dp[n-1] + dp[1]*dp[n-2] + dp[2]*dp[n-3] + … + dp[n-1]*dp[0]

------------------------------------------------------------

代码

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=0; j<i; j++)
            {
                dp[i] += dp[j] * dp[i-1-j];
            }
        }
        return dp[n];
    }
}

猜你喜欢

转载自blog.csdn.net/da_kao_la/article/details/89049236