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,2,...,i,...n来说,二分查找书的个数等于所有已i为根节点的二分查找树的个数之和。而以i为根节点,不同左子树的数目为d[i-1],不同右子树的数目为d[n-i+1],这都是d[i]的子问题,因此可以通过动态规划来求解。
class Solution {
public:
int numTrees(int n) {
if(n<1){
return 1;
}
int d[n + 1];
memset(d, 0, sizeof(int) * (n+1));
d[0] = 1;
for(int i=1; i<=n; i++){
for(int j=0; j<i; j++){
d[i] += d[j]*d[i-j-1];
}
}
return d[n];
}
};版权声明:本文为博主原创文章,未经博主允许不得转载。
[LeetCode] Unique Binary Search Trees
原文地址:http://blog.csdn.net/kangrydotnet/article/details/47316833