[LeetCode][JavaScript]Unique Binary Search Trees

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

https://leetcode.com/problems/unique-binary-search-trees/
 
 
 
 
 

 

 

生成n个节点的二叉排序树,只要求出个数。

从1到n遍历,选当前的点为根,比根小的在左子树,比根大的在右子树。

如果用递归,有很多重复计算的子树会TLE,改用DP,记住之前算过的节点。

 

 1 /**
 2  * @param {number} n
 3  * @return {number}
 4  */
 5 var numTrees = function(n) {
 6     var dp = [1, 1, 2], i, j, left, right, sum;
 7     for(i = 3; i <= n; i++){
 8         sum = 0;
 9         for(j = 0; j < i; j++){
10             left = dp[j];
11             right = dp[i - j - 1];
12             sum += left * right;
13         }
14         dp[i] = sum;
15     }
16     return dp[n];
17 };

 

TLE:

 

 1 /**
 2  * @param {number} n
 3  * @return {number}
 4  */
 5 var numTrees_TLE = function(n) {
 6     var target = [];
 7     for(var i = 1; i <= n; i++){
 8         target.push(i);
 9     }
10     return getNum(target);
11 
12     function getNum(arr){
13         var sum = 0, left, right;
14         if(arr.length === 2){
15             return 2;
16         }else if(arr.length <= 1){
17             return 1;
18         }
19         for(var i = 0; i < arr.length; i++){
20             left = getNum(arr.slice(0, i));
21             right = getNum(arr.slice(i + 1, arr.length));
22             sum += left * right;
23         }
24         return sum;
25     }
26 };

 

 

 

 

 

 

 

posted @ 2015-11-08 22:02  `Liok  阅读(362)  评论(0编辑  收藏  举报