您的位置:首页 > 产品设计 > UI/UE

leetcode96. Unique Binary Search Trees

2016-07-10 11:29 483 查看
题目链接:https://leetcode.com/problems/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


题目大意:给一个数字n,那么有n个结点的二叉查找树共有多少棵。结点val对应从1到n。

这道题看了很多博客,也算是搞懂了,总结一下就是:

选取一个结点为根,就把结点切成左右子树,以这个结点为根的可行二叉树数量就是左右子树可行二叉树数量的乘积,所以总的数量是将以所有结点为根的可行结果累加起来。

大概也是使用动态规划,n=3的过程如下:

//r1+=r0*r0;r1=1
//r2+=r0*r1 r2=1
//r2+=r1*r0 r2=2
//r3+=r0*r2 r3=2
//r3=r1*r1 r3=3
//r3+=r2*r9 r3=5


代码如下:

public class Solution {
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-j-1];
}
}
return res
;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode