leetcode || 96、Unique Binary Search Trees
·
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
Tree Dynamic Programming
题意:大小为N的没有重复元素的数组,求其可以构成二查搜索树的数量
thinking:
(1)求数量,用DP
(2)刚开始用递归,提交超时
(3)DP的思路是遍历所有子结构,用一个数组保存中间结果,加速求解过程。
code:
DP:
class Solution {
public:
int numTrees(int n) {
vector<int> num;
num.push_back(1);
for(int i=1; i<=n; i++){
num.push_back(0);
if(i<3)
num[i]=i;
else{
for(int j=1; j<=i; j++)
num[i]+=num[j-1]*num[i-j];
}
}
return num[n];
}
};
更多推荐



所有评论(0)