资讯专栏INFORMATION COLUMN

[Leetcode-Dynamic Programming]Unique Binary Search

MartinDai / 1640人阅读

Unique Binary Search Trees
Given n, how many structurally unique BST"s (binary search trees) that store values 1...n?

For example,
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
   

1.解题思路

本题求1...n可以组成的二叉搜索树的种数,我们很容易想到用动态规划来做,寻找状态,dp[i]来表示1..i个节点可以有的种数,状态转移,我们可以发现对于每一个根节点,它所能出现的二叉树种类就等于它的左子树种类*它的右子树种类,而且i来说,可以选取1..i中的任意一个节点作为根。
状态转移方程就出来了。
dp[i]+=dp[root-1]*dp[i-root]; 1<=root<=i;

2.代码

public class Solution {
    public int numTrees(int n) {
        if(n==0) return 0;
        int[] dp=new int[n+1];
        dp[0]=1;
        for(int i=1;i<=n;i++){
           for(int root=1;root<=i;root++){
               dp[i]+=dp[root-1]*dp[i-root];
           }
        }
        return dp[n];
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/69813.html

相关文章

  • [LeetCode] 96. Unique Binary Search Trees I &

    Unique Binary Search Trees Problem Given n, how many structurally unique BSTs (binary search trees) that store values 1...n? Example Given n = 3, there are a total of 5 unique BSTs. 1 3 3...

    nidaye 评论0 收藏0
  • [Leetcode] Unique Binary Search Trees 唯一二叉搜索树

    摘要:而根可以选择从到的任意的数,唯一二叉树的总数,就是根为到的树相加。所以该问题化简为以为根,其唯一左子树和右子树各有多少,这就是个动态规划的问题了。 Unique Binary Search Trees I && II 解法请见:https://yanjia.li/zh/2019/02/... Given n, how many structurally unique BSTs (b...

    enrecul101 评论0 收藏0
  • leetcode-95-Unique Binary Search Trees II

    摘要:题目解读穷举列出所有二叉树的结构类型。重点动态规划,关注临近,,之间的关系应用穷举组合,动态规划穷举组合,适用于相邻元素有规律。处注意边界值的情况。不能有重复,遗漏。 题目解读: 穷举列出所有二叉树的结构类型。重点: 动态规划,关注临近root,left,right之间的关系应用:穷举组合,动态规划穷举组合,适用于相邻元素有规律。bug处:注意边界值的情况。不能有重复,遗漏。 clas...

    Tony_Zby 评论0 收藏0
  • [Leetcode] Closest Binary Search Tree Value 最近二叉搜索

    摘要:递归法复杂度时间空间思路根据二叉树的性质,我们知道当遍历到某个根节点时,最近的那个节点要么是在子树里面,要么就是根节点本身。因为我们知道离目标数最接近的数肯定在二叉搜索的路径上。 Closest Binary Search Tree Value I Given a non-empty binary search tree and a target value, find the va...

    AlphaWallet 评论0 收藏0
  • [LintCode] Remove Node in Binary Search Tree [理解BS

    Problem Given a root of Binary Search Tree with unique value for each node. Remove the node with given value. If there is no such a node with given value in the binary search tree, do nothing. You sho...

    陈江龙 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<