zoukankan      html  css  js  c++  java
  • Leetcode 96. Unique Binary Search Trees

    96. Unique Binary Search Trees

    • Total Accepted: 91481
    • Total Submissions: 238129
    • Difficulty: Medium

    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

    思路:本质是DP。假设n个结点产生的二叉查找树的个数为f[n]。

    f[0]=1

    n个结点的时候

    根结点为1,这时有f[0]*f[n-1]种情况

    根结点为2,这时有f[1]*f[n-2]种情况

    根结点为3,这时有f[2]*f[n-3]种情况

    ...

    根结点为n-1,这时有f[n-2]*f[1]种情况

    根结点为n,这时有f[n-1]*f[0]种情况

    所以总共有f[n]=f[0]*f[n-1]+f[1]*f[n-2]+f[3]*f[n-3]+...+f[n-3]*f[3]+f[n-2]*f[1]+f[n-1]*f[0]。(n>=2)

    其实上面的f[n]所形成的序列就是Catalan number,公式是C(2n,n)/(n+1)。这就是方法二。不过用数学公式计算的时候,要注意整数相除和溢出问题。

    代码:

    方法一:直接计算。

     1 class Solution {
     2 public:
     3     int numTrees(int n) {
     4         vector<int> nums(n+1,0);
     5         nums[0]=1;
     6         int res=1;
     7         for(int i=1;i<=n;i++){
     8             for(int j=0;j<i;j++){
     9                 nums[i]+=nums[j]*nums[i-1-j];
    10             }
    11         }
    12         return nums[n];
    13     }
    14 };

    方法二:用Catalan number公式计算。注意整数相除和溢出问题

     1 class Solution {
     2 public:
     3     int numTrees(int n) {
     4         long long ans=1,i;//注意溢出问题
     5         for(i=1;i<=n;i++){
     6             ans=ans*(n+i)/i;
     7         }
     8         return ans/i;
     9     }
    10 };
  • 相关阅读:
    matplotlib数据可视化之柱形图
    xpath排坑记
    Leetcode 100. 相同的树
    Leetcode 173. 二叉搜索树迭代器
    Leetcode 199. 二叉树的右视图
    Leetcode 102. 二叉树的层次遍历
    Leetcode 96. 不同的二叉搜索树
    Leetcode 700. 二叉搜索树中的搜索
    Leetcode 2. Add Two Numbers
    Leetcode 235. Lowest Common Ancestor of a Binary Search Tree
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5751739.html
Copyright © 2011-2022 走看看