LeetCode OJ 96. 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

 

 

我们观察一下BST的构成,对于任意一个节点,它的左子树上的所有值都比它小,它的右子树上的值都比它大。对于1···n,我们任选其中一个值i作为根节点,则小于i的有i-1个值,大于i的有n-1个值,因此对于以i为根节点这种情况,共计有numTrees(i-1)*numTrees(n-i)种可能。有了这种思路我们就可以递归求解。

但是这样的递归过程会重复做许多不必要的工作,例如n=5时,假设我们以3为根节点,会两次计算numTrees(2)。求一个大的值,我们会多次求解多个小的值,如果能把这些小值的解保存下来,就会节省很多时间。代码如下:

 1 public class Solution {
 2     public HashMap<Integer, Integer> map = new HashMap();
 3     public int numTrees(int n) {
 4         map.put(0, 1);
 5         map.put(1, 1);
 6         if(map.containsKey(n)) return map.get(n);
 7         
 8         int count = 0;
 9         for(int i = 1; i<=n; i++){
10             int left = map.containsKey(i-1)?map.get(i-1):numTrees(i-1);
11             int right = map.containsKey(n-1)?map.get(n-i):numTrees(n-i);
12             count += left*right;
13         }
14         map.put(n,count);
15         return count;
16     }
17 }

 

posted @ 2016-05-03 10:28  Black_Knight  阅读(169)  评论(0编辑  收藏  举报