[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 };

 

 
posted @ 2014-03-07 09:27  青轰的后花园  阅读(150)  评论(0编辑  收藏  举报