首页 > 其他 > 详细

96. Unique Binary Search Trees

时间:2018-09-17 13:00:25      阅读:149      评论:0      收藏:0      [点我收藏+]

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

原文:https://www.cnblogs.com/goPanama/p/9661478.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!