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、我的思考
https://leetcode-cn.com/problems/unique-binary-search-trees/solution/hua-jie-suan-fa-96-bu-tong-de-er-cha-sou-suo-shu-b/