• 【LeetCode】96. 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

    提示:

    这道题可以用动态规划的思路解决。既然动态规划的核心是把问题拆分成子问题,考虑到BST的特性,我们可以得到如下推导公式:

    F(i, n) = G(i-1) * G(n - i)

    F(i, n)的含义是:以i为根节点,且总共有n个节点的树。例如F(2,3)就是说以2为根节点,总共有3个节点,那么其实就只有一种情况,即:

          2
         / 
        1   3

    由于BST的特性,所以当树以i为节点时,左子树会有i-1个节点,右子树则会有n-i个节点,很容易联想到G(n)的含义为:总数为n个节点的BST有多少种可能,那么当我们将G(i-1) * G(n - i)相乘时,得到的就是左右子树总共可能的组合。

    至此,dp的状态方程就已经很明了了。

    代码:

     1 class Solution {
     2 public:
     3     int numTrees(int n) {
     4         vector<int> dp(n+1, 0);
     5         dp[0] = dp[1] = 1;
     6         dp[2] = 2;
     7         for (int i = 3; i <= n; ++i) {
     8             for (int j = 1; j <= i; ++j) {
     9                 dp[i] += dp[j-1] * dp[i-j];
    10             }
    11         }
    12         return dp[n];
    13     }
    14 };
  • 相关阅读:
    MySql 数据备份与还原
    PHP 连接数据库
    迭代法写线性回归
    ML numpy、pandas、matplotlib的使用
    005 动态加载实例
    爬虫实现案例
    004 使用scrapy框架爬虫
    003 爬虫持久化的三个不同数据库的python代码
    内置函数和匿名函数
    迭代器和生成器
  • 原文地址:https://www.cnblogs.com/jdneo/p/5226616.html
Copyright © 2020-2023  润新知