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

96. Unique Binary Search Trees

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

标签:+=   for   math   .com   arch   binary   span   lin   bsp   

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

标签:+=   for   math   .com   arch   binary   span   lin   bsp   

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

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