[leetcode-96]Unique Binary Search Trees(c++)

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

For example,
Given n = 3, there are a total of 5 unique BST’s.

1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
Show Tags
Show Similar Problems

分析:这道题蛮有意思的,我当时的第一个想法是用递归找到所有的数据,但是一想只要找到总数即可,那么就得去找规律。
这个题需要使用DP算法,需要查找的数为n,那么根节点可以取的值为1,2,,,n。然后当选定了1或n时,其余值都在树的某一边,总共有多少种类呢?numTree(n-1)。但是我们已经DP了,所以为num[n-1]。与此同时,对于中间节点。比如i,那么左侧有1,2,,,i-1.右侧有i+1,i+2,,,n。所以左侧有num[i-1]种选择,右侧有num[n-i]中选择。相乘并相加得到最后结果。
时间复杂度为O(n2),空间复杂度为O(n)

代码如下:0ms

class Solution {
public:
    int numTrees(int n) {
        int *nums = new int[n+1]();
        nums[1] = 1;
        int left, right;
        for (int i = 2; i <= n; i++) {
            nums[i] += nums[i - 1]*2;//left edge and right edge
            for (int j = 2; j < i; j++) {
                left = j - 1;
                right = i - j;
                nums[i] += nums[left] * nums[right];
            }
        }
        return nums[n];
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值