IncredibleThings

导航

LeetCode - Unique Binary Search Trees

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;
    }
    
}

 Recursion with Memoization

class Solution {
    Map<Integer, Integer> cache = new HashMap<>();
    public int numTrees(int n) {
        if (n == 1) {
            return 1;
        }
        if (cache.containsKey(n)) {
            return cache.get(n);
        }
        int res = 0;
        for (int i = 1; i <= n; i++) {
            int right = numTrees(n-i);
            int left = numTrees(i-1);
            if (left == 0) {
                res = res + right;
            } 
            else if (right == 0) {
                res = res + left;
            } 
            else {
                res = res + left * right;
            }
        }
        cache.put(n, res);
        return res;
    }
}

 

posted on 2021-02-19 16:02  IncredibleThings  阅读(28)  评论(0编辑  收藏  举报