*[Lintcode]Unique Binary Search Trees 不同的二叉查找树

Given n, how many structurally unique BSTs (binary search trees) that store values 1...n?

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
分析:递归法。n=19时超时.

public class Solution {
    /**
     * @paramn n: An integer
     * @return: An integer
     */
    public int numTrees(int n) {
        if(n == 0 || n == 1) return 1;
        return helper(n, 1, n);
    }
    
    int helper(int n, int start, int end) {
        if(start == end) return 1;
        int res = 0;
        for(int i = start; i <= end; i++) {
            int left = 1, right = 1;
            if(i > start) left = helper(n, start, i - 1);
            if(i < end) right = helper(n, i + 1, end);
            res += left * right;
        }
        return res;
    }
}

网上看了一下,可以使用一维动态规划。res[i]代表n=i时,不同排列数量。res[i] = res[0]*res[i-1] + res[1]*res[n-2] ......

其中res[0]*res[n-1]代表i做root时,左边0个点,右边n-1个点时的排列数。在考虑解法时,要忽略掉数字。

public class Solution {
    /**
     * @paramn n: An integer
     * @return: An integer
     */
    public int numTrees(int n) {
        if(n == 0 || n == 1) return 1;
        int[] res = new int[n + 1];
        res[0] = 1;
        
        for(int i = 1; i <= n; i++) {
            for(int j = 0; j < i; j++) {
                res[i] += res[j] * res[i - 1 - j];
            }
        }
        return res[n];
    }
}





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值