【Leetcode】之Unique Binary Search Trees

一.问题描述

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

二.我的解题思路

对于这样的题目,首先自然是分析问题。如果让我去做这个问题,我会以根元素作为出发点,对于从1-n的每一个元素,都可以作为根节点。确定根节点i之后,自然左子树应该放1...i-1(T(I-1))、右子树应该放i+1...n(T(n-i))。这样就能写出递归关系了。

但是如果直接用分治递归做会有很多重复的子问题,所以对本题适合采用动态规划的算法思想。测试通过的程序如下:

class Solution {
public:
    int numTrees(int n) {
        int * tmp = new int[n+1];
        tmp[0]=1;tmp[1]=1;tmp[2]=2;
        int i=3;
        int res;
        while(i<=n){
            tmp[i]=0;
            for(int j=1;j<=i;j++)
                tmp[i]+=tmp[i-j]*tmp[j-1];
        
            i++;        
        }
        return tmp[n];
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值