【LeetCode记录】96. Unique Binary Search Trees

96. Unique Binary Search Trees

题目描述

Given n, how many structurally unique BST’s (binary search trees) that store values 1 … n?

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/unique-binary-search-trees

递推

思路:当构造二叉排序树时,确定了根节点之后,左右子树仍然为二叉排序树,且规模更小。故使用一个数组来记录有n个数时可构造不同的二叉排序树的个数。

int numTrees(int n){
    if(n == 0)return 0;
    if(n == 1)return 1;
    int *f = (int*)malloc((n+1)*sizeof(int));
    f[0] = 1;
    f[1] = 1;
    int i,j;
    int sum = 0;
    for(j = 2; j < n+1; j++){
        for(i = 1; i < j+1; i++){
            sum = sum + (f[i-1]*f[j-i]);
        }
        f[j] = sum;
        sum = 0;
    }
    return f[n];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值