We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
出处:LeetCode 算法第96题 给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种? 示例: 输入: 3 输出: 5 解释: 给定 n = 3, 一共有 5 种不同结构的二叉搜索树: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
出处:LeetCode 算法第96题
给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种?
示例:
输入: 3 输出: 5 解释: 给定 n = 3, 一共有 5 种不同结构的二叉搜索树: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
采用动态规划的方法,因为固定个数的节点能组成的二叉搜索树是确定的,所有将n个数通过i分成左右子树,再将左右子树的值相乘即可,最后将所有i的情况相加,即为总的个数。如果不采用动态规划,会产生大量的重复计算,采用动态规划,通过空间换时间的方式,可以大大减少运算量
/** * @param {number} n * @return {number} */ var numTrees = function (n) { var dp = new Array(n + 1).fill(undefined); dp[0] = 1; dp[1] = 1; dp[2] = 2; for (var i = 3; i <= n; i++) { var temp = 0; for (var j = 1; j <= i; j++) { temp += dp[j -1]*dp[i - j]; } dp[i] = temp; } return dp[n]; }; console.log(numTrees(4));
The text was updated successfully, but these errors were encountered:
No branches or pull requests
习题
思路
采用动态规划的方法,因为固定个数的节点能组成的二叉搜索树是确定的,所有将n个数通过i分成左右子树,再将左右子树的值相乘即可,最后将所有i的情况相加,即为总的个数。如果不采用动态规划,会产生大量的重复计算,采用动态规划,通过空间换时间的方式,可以大大减少运算量
解答
The text was updated successfully, but these errors were encountered: