Unique Binary Search Trees I

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

Solution: dp.
http://fisherlei.blogspot.com/2013/03/leetcode-unique-binary-search-trees.html

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

 

posted @ 2014-04-04 08:34  beehard  阅读(145)  评论(0编辑  收藏  举报