Unique Binary Search Trees
Total Accepted: 48675 Total Submissions: 134436My Submissions
Question Solution
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
Hide Tags
Have you met this question in a real interview?
Yes
No
这道题开始没想到,看到别人文章上的算法,才知道怎么去用动态规划的思想来解题,首先,二分查找树的定义是,左子树节点均小于root,右子树节点均大于root!不要想当然地将某个点作为root时,认为其他所有节点都能全部放在left/right中,除非这个点是 min 或者 max 的。
当选定一个根节点时,为左子树那边的种类*右子树那边的种类,
所以可以先计算少的点数,再接着记录下来,然后一步步往上计算
#include<iostream> #include<vector> using namespace std; int numTrees(int n) { if(n==0||n==1) return 1; vector<int> temp; temp.push_back(1); temp.push_back(1); for(int i=2;i<=n;i++) { int result_temp=0; for(int j=1;j<=i;j++) result_temp+=temp[j-1]*temp[i-j]; temp.push_back(result_temp); } return temp[n]; } int main() { cout<<numTrees(3)<<endl; }
时间: 2024-12-08 22:01:36