【Leetcode】96. Unique Binary Search Trees
Given n, how many structurally unique BST’s(binary search trees) that store values 1 … n?
Example:
Input: 3
Output: 5
Explanation:
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…n可以组成多少个BST(二叉搜索树)。
解题思路:
1…n中每个节点都当作根节点,左右两边分别为先前已得到的结果,左右两边的个数相乘。保存当前位置的结果。
faster than 100%
class Solution {
public:
int numTrees(int n) {
vector<int> ans;
ans.push_back(1);
for(int i = 1;i<=n;i++){
int start = 1, end = i;
int tmp = 0;
for(int j = 1;j<=i;j++){
int l = j-start;
int r = end - j;
tmp += (ans[l]*ans[r]);
}
ans.push_back(tmp);
}
return ans[n];
}
};
还没有评论,来说两句吧...