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

LeetCode - Unique Binary Search Trees

时间:2021-02-20 12:13:36      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:ons   div   style   tco   time   class   put   sea   span   

Given an integer n, return the number of structurally unique BST‘s (binary search trees) which has exactly n nodes of unique values from 1 to n.

 

Example 1:


Input: n = 3
Output: 5
Example 2:

Input: n = 1
Output: 1
 

Constraints:

1 <= n <= 19

Recursion, Time-out

class Solution {
    public int numTrees(int n) {
        int res = 0;
        for (int i = 1; i <= n; i++) {
            res = res + helper(i, n, 1);
        }
        return res;
    }
    
    public int helper(int current, int h, int l) {
        if (h == l && current == l) {
            return 1;
        }
        int left = 0;
        for (int i = l; i< current; i++) {
            left = left+ helper(i, current-1, l);
        }
        
        int right = 0;
        for (int i = h; i > current; i--) {
            right = right + helper(i, h, current+1);
        }
        if (left == 0) {
            return right;
        }
        if (right == 0) {
            return left;
        }
        return left * right;
    }
    
}

 

LeetCode - Unique Binary Search Trees

标签:ons   div   style   tco   time   class   put   sea   span   

原文地址:https://www.cnblogs.com/incrediblechangshuo/p/14416563.html

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