[Leetcode] #96 Unique Binary Search Trees

来源:互联网 发布:协方差矩阵特征值分解 编辑:程序博客网 时间:2024/04/28 16:38

Discription:

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

Solution:

分别以1到n这n个数分别为根节点,求其二叉搜索树的个数,求其总和。对于每个根节点的二叉树的数目等于左子树的个数乘以右子树的数目,这里通过动态规划求出不同个数结点所构成二叉搜索树的数目并加以保存。

#include<iostream>#include<vector>using namespace std;int numTrees(int n) {vector<int> res;res.push_back(1);for (int i = 1; i <= n; i++){int num = 0;for (int j = 1; j <= i; j++){num += res[j - 1] * res[i - j];}res.push_back(num);}return res[n];}int main(){cout << numTrees(3) << endl;cin.get();return 0;}


0 0