用动态规划解决二叉查找树

问题描述

我的解决方法:


package algorithm;

/**
 * 
 * @author wuxingye
 * @problem 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
 */
public class UniqueBinarySearchTrees {
	public static void main(String[] args) {
		System.out.println(numTrees(18));
	}

	public static int numTrees(int n) {
		int[] record = new int[n + 1];// 记录已经计算过的值
		record[0] = 1;// 0个被计算或者1个被计算,输出的值都为1
		record[1] = 1;
		return numTrees(n, record);
	}

	public static int numTrees(int n, int record[]) {
		int result = 0;
		for (int i = 1; i <= n; i++) {
			// 以根元素为分界线,规划左右子树
			int left = record[i - 1];
			int right = record[n - i];
			// 计算左右子树的值,结果相乘
			result += (left > 0 ? left : numTrees(i - 1, record))
					* (right > 0 ? right : numTrees(n - i, record));

		}
		// 将结果记录下来
		record[n] = result;
		return result;
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值