1、题目描述
给定一个整数 n,求以 1 … n 为节点组成的二叉搜索树有多少种?
示例:
输入: 3
输出: 5
解释:
给定 n = 3, 一共有 5 种不同结构的二叉搜索树:
1 3 3 2 1
/ / /
3 2 1 1 3 2
/ /
2 1 2 3
2、我的代码
class Solution {
public:int numTrees(int n) {int* G = (int*) malloc(sizeof(int)*(n+1));G[0] = 1;G[1] = 1;for(int i = 2;i <= n;++i){for(int j = 1;j <= i; ++j){G[i] += G[j-1]*G[i-j];}}return G[n];}
};
3、网上好的解法
public class Solution {public int numTrees(int n) {int[] G = new int[n + 1];G[0] = 1;G[1] = 1;for (int i = 2; i <= n; ++i) {for (int j = 1; j <= i; ++j) {G[i] += G[j - 1] * G[i - j];}}return G[n];}
}
4、自己可以改进的地方
Line 10: Char 22: runtime error: signed integer overflow: -4702111234474983746 + -4702111234474983744 cannot be represented in type 'long long' (solution.cpp)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:20:22
5、优化代码至简无可简
class Solution {
public:int numTrees(int n) {unsigned int* G = (unsigned int*) malloc(sizeof(unsigned int)*(n+1));memset(G,0x0,(sizeof(unsigned int)*(n+1)));G[0] = 1;G[1] = 1;for(int i = 2;i <= n;++i){for(int j = 1;j <= i; ++j){G[i] += G[j-1]*G[i-j];}}return G[n];}
};
6、我的思考
/
本文发布于:2024-01-28 09:10:04,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/17064042086341.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |