题目地址
https://leetcode-cn.com/problems/unique-binary-search-trees/
题目描述
给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种?
示例:
输入: 3
输出: 5
解释:
给定 n = 3, 一共有 5 种不同结构的二叉搜索树:
   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3
题解
递归解法
定义递归函数
public int build(int left, int right),用来描述通过[left, right]构建的所有二叉搜索树的数量。
class Solution {
    public int numTrees(int n) {
        return build(1, n);
    }
    public int build(int left, int right) {
        if (left == right) return 1;
        if (left > right) return 1; // null 子树也属于一棵树
        int numTrees = 0;
        for (int i = left; i <= right; ++ i) {
            // [left, i-1] 表示左子树
            int numLeftTrees = build(left, i-1);
            // [i+1, right] 表示右子树
            int numRightTrees = build(i+1, right);
            numTrees += numLeftTrees * numRightTrees;
        }
        return numTrees;
    }
}

耗时非常长
通过 memo 剪枝
class Solution {
    public int numTrees(int n) {
        int[][] memo = new int[n+1][n+1];
         for (int i = 0; i <= n; i++) {
            Arrays.fill(memo[i], -1);
        }
        return build(1, n, memo);
    }
    public int build(int left, int right, int[][] memo) {
        if (left == right) return 1;
        if (left > right) return 1; // null 子树也属于一棵树
        if (memo[left][right] != -1) {
            return memo[left][right];
        }
        int numTrees = 0;
        for (int i = left; i <= right; ++ i) {
            // [left, i-1] 表示左子树
            int numLeftTrees = build(left, i-1, memo);
            // [i+1, right] 表示右子树
            int numRightTrees = build(i+1, right, memo);
            numTrees += numLeftTrees * numRightTrees;
        }
        memo[left][right] = numTrees;
        return numTrees;
    }
}

执行时间瞬间下降。