zoukankan      html  css  js  c++  java
  • [leetCode]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


    主要是递归的思想,大数的分支都是小树组成的,存在组合思想的都可以考虑递归。将一个大数划分为小数的集合,自己写个n=3,n=5的就可以知道了,使用map容器可以极大提高效率
     1 #include <iostream>
     2 #include <map>
     3 using namespace std;
     4 class Solution {
     5 public:
     6     map<int,int> imap;
     7     map<int,int> ::iterator iter;
     8     int numTrees(int n) {
     9         if(n <= 0)    return 0;
    10         return pathNumcalc(n);
    11     }
    12 private:
    13     int pathNumcalc(int n){
    14         int left,right,sum;
    15         left = right = sum = 0;
    16         iter = imap.find(n);
    17         if(iter != imap.end()) return iter->second;
    18         if(n == 0)    sum = 0;
    19         if(n == 1)  sum = 1;
    20         for(int i = 1; i <= n; i++){
    21             left = pathNumcalc(i-1);
    22             right = pathNumcalc(n-i);
    23             if(left == 0)        sum+=right;
    24             else if(right == 0)    sum+=left;
    25             else sum+=left*right;
    26         }
    27         imap.insert(pair<int,int>(n,sum));
    28         return sum;
    29     }
    30 };
     
    艰难的成长
  • 相关阅读:
    CSS处理小技巧
    React 脚手架构建
    Tomcat8学习
    javaScript(ES5中的类,原型,原型对象和函数对象的关系)
    保留两位小数(逢5进位,精度不会丢失)
    获取过去12个月
    mybatis 踩坑记录
    动态代理--jdk和cglib
    lambda表达式
    mybatis的mapper映射配置文件详解
  • 原文地址:https://www.cnblogs.com/marylins/p/3585736.html
Copyright © 2011-2022 走看看