给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种?
示例:
输入: 3 输出: 5 解释: 给定 n = 3, 一共有 5 种不同结构的二叉搜索树: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
class Solution { public int numTrees(int n) { if (n <= 1) { return 1; } int[] dp = new int[n + 1]; dp[0] = 1; for (int i = 1; i <= n; i++) { int count = 0; for (int j = 1; j <= i; j++) { count += dp[j - 1] * dp[i - j]; } dp[i] = count; } return dp[n]; } }
转载于:https://www.cnblogs.com/JAYPARK/p/10703041.html
原文链接:https://blog.csdn.net/weixin_30342827/article/details/95879017
本站声明:网站内容来源于网络,如有侵权,请联系我们,我们将及时处理。
还没有人抢沙发呢~