其他分享
首页 > 其他分享> > LeetCode96. 不同的二叉搜索树

LeetCode96. 不同的二叉搜索树

作者:互联网

题目

https://leetcode-cn.com/problems/unique-binary-search-trees/

思路

可以采用分治的思想:将原问题拆分为各种子问题,逐一求解子问题并合并子问题的解,从而得到原问题的解
分治一般伴随着递归。
分治最主要的是要想方设法合并子问题的解,也就是使用具体的数据结构进行数据记录,不要陷入具体的递归细节。

代码

class Solution {
    public int numTrees(int n) {
        int sum = 0;
        if (n == 0) return 1;
        if (n <= 2) return n;
        for (int i = 1; i <= n; i++) {
            sum += numTrees(i - 1) * numTrees(n - i);
        }
        return sum;
    }
}

标签:cn,递归,int,分治,合并,LeetCode96,二叉,问题,搜索
来源: https://www.cnblogs.com/mirage-mc/p/15823668.html