码迷,mamicode.com
首页 > 其他好文 > 详细

Unique Binary Search Trees

时间:2016-08-07 06:22:24      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:

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

 

Analyse: We can select 1~N as the root. Suppose the root is i, then we can put j = 0~i - 1 nodes in its left, and put i - j - 1 nodes in its right. 

Runtime: 0ms.

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

 

 

Unique Binary Search Trees

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/5745321.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!