zoukankan      html  css  js  c++  java
  • [LeetCode] Unique Binary Search Tree

    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
    

     解题思路:

    设有n个结点的二叉查找树有b[n]个,则设想对一个排好序的list,我们从第一个元素开始枚举根节点。对于每一个根节点,这棵二叉查找树的可能是b[left] * b[right], left < n, right < n。

    故我们只需要取b[0] = 0, b[1] = 1, 然后迭代计算b[i]即可。

    class Solution {
    public:
        int numTrees(int n) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            if(n == 0)
                return 0;
            
            int *num;
            num = new int[n + 1];
            num[0] = 1;
            num[1] = 1;
            for(int i = 2;i <= n;i++)
            {
                num[i] = 0;
                for(int j = 0;j < i;j++)
                    num[i] += num[j] * num[i - 1 - j];
            }
            
            return num[n];
        }
    };
  • 相关阅读:
    螺旋矩阵算法
    shell脚本编程的10个最佳实践
    时间字符串转长整形数
    python的发音
    wget使用技巧
    History命令用法15例
    14位格式时间字符串
    Spring MVC
    Android SQLite数据储存方式
    MYSQL命令大全
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3415494.html
Copyright © 2011-2022 走看看