码迷,mamicode.com
首页 > 其他好文 > 详细

96.Unique Binary Search Trees

时间:2015-01-30 22:53:46      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

Given n, how many structurally unique BST‘s (binarysearch 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

HideTags

 Tree Dynamic Programming


#pragma once
#include<queue>
#include<iostream>
using namespace std;

int numTrees(int n) {
	int *a=new int[n+1];
	for (int i = 0; i < n + 1; i++)
		a[i] = 0;
	a[0] = 0;
	a[1] = 1;
	for (int i = 1; i <= n; i++)
	{
		for (int j = 2; j < i; j++)
			a[i] += (a[j - 1] * a[i - j]);//掐头去尾后,2至i-1做根节点时的可能数
		a[i] += 2 * a[i - 1];//a[0]=0不能与a[i]相乘后叠加,掐头去尾单独算
	}
	return a[n];
}

void main()
{
	cout << numTrees(1) << endl;
	cout << numTrees(2) << endl;
	cout << numTrees(3) << endl;
	cout << numTrees(4) << endl;
	system("pause");

}


96.Unique Binary Search Trees

标签:

原文地址:http://blog.csdn.net/hgqqtql/article/details/43308187

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!