经典算法不同的二叉搜索树

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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值