• LeetCode96 Unique Binary Search Trees


    题目:

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

    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
    

    分析:

    考察用n个节点组成的BST的个数与1...n-1之间的关系。

    枚举每一个节点作为其根节点即可得到,dp[n] = dp[0] * dp[n - 1] + dp[1] * dp[n - 2] + ... + dp[n - 1] * dp[0];

    代码:

     1 class Solution {
     2 public:
     3     int numTrees(int n) {
     4         int dp[n + 1] = {0};
     5         dp[0] = 1;
     6         dp[1] = 1;
     7         for (int i = 2; i <= n; ++i) {
     8             for (int j = 0; j < i; ++j) {
     9                 dp[i] += (dp[j] * dp[i - 1 - j]);
    10             }
    11         }
    12         return dp[n];
    13     }
    14 };
  • 相关阅读:
    yii分页
    ajax分页
    批删,全选
    网站开发的愿景
    margin collapse 坍塌
    URI URL URN
    Servlet
    Http请求
    进程间通信
    网络编程
  • 原文地址:https://www.cnblogs.com/wangxiaobao/p/5998469.html
Copyright © 2020-2023  润新知