96. Unique Binary Search Trees

Posted gopanama

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了96. Unique Binary Search Trees相关的知识,希望对你有一定的参考价值。

https://leetcode.com/problems/unique-binary-search-trees/discuss/31666/DP-Solution-in-6-lines-with-explanation.-F(i-n)-G(i-1)-*-G(n-i)

 

 

 

 1 //用dp[]做cache 否则会超过time limit
 2 class Solution {
 3     int[] dp;
 4     public int numTrees(int n) {
 5         dp = new int[n];
 6         return helper(1, n);
 7         
 8     }
 9     
10     public int helper(int lo, int hi) {
11         if(lo >= hi) return 1;
12         int res = 0;
13         if(dp[hi - lo] != 0) return dp[hi - lo];
14         for(int i = lo; i <= hi; i++) {
15             res += helper(lo, i-1) * helper(i+1, hi);
16             
17         }
18         dp[hi - lo] = res;
19         return res;
20     }
21 }
22 
23 
24 //神奇的math 
25 class Solution {
26     public int numTrees(int n) {
27         int[] res = new int[n+1];
28         res[0] = 1;
29         res[1] = 1;
30         for(int i = 2; i <= n; i++) {
31             for(int j = 0; j <= i; j++) {
32                 res[i] = res[j - 1] * res[i - j]; 
33             }
34         }
35         return res[n];
36         
37     }
38     
39 }

 

以上是关于96. Unique Binary Search Trees的主要内容,如果未能解决你的问题,请参考以下文章

#Leetcode# 96. Unique Binary Search Trees

96. Unique Binary Search Trees

96. Unique Binary Search Trees

96. Unique Binary Search Trees

96. Unique Binary Search Trees

[动态规划] leetcode 96 Unique Binary Search Trees