[LeetCode] Unique Binary Search Trees n结点二叉搜索树的数目

来源:互联网 发布:做淘宝刷客的被骗经历 编辑:程序博客网 时间:2024/04/27 07:35

声明:原题目转载自LeetCode,解答部分为原创

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

Solution:

        思路:

        想法一:递归求解。首先用数组tree_n[] 记录不同节点数能建立的二叉搜索数的个数。对于n个结点的二叉搜索树,若以顺序第 i 个结点为根,可以创建的二叉搜索树的数量为tree_n[ i - 1 ] * tree_n[ n - i ]。算法缺点是时间复杂度较高。

        代码如下:

#include<iostream>#include<vector>using namespace std; class Solution {public:    int numTrees(int n) {        return root_n(n);     }    private:        int root_n(int n)        {        if(n == 0 || n == 1)        return 1;                int num = 0;        for(int i = 1 ; i <= n ; i ++)        {        num += root_n(i - 1) * root_n(n - i);}return num;}};int main(){Solution text;cout << "numTrees(3) : " << text.numTrees(3) << endl;cout << "numTrees(4) : " << text.numTrees(4) << endl;}

          想法二:基于想法一的基础上,考虑如何减少调用递归的次数,即每次递归后要记录相关数值,用于下一次递归应用。同时,根据想法一的实现公式的特点,采用线性代数矩阵相乘的方式来实现。

          代码如下:

#include<iostream>#include<vector>using namespace std; class Solution {public:    int numTrees(int n) {    vector<int> tree_n;tree_n.push_back(1);tree_n.push_back(1);for(int i = 2 ; i <= n ; i ++){int num = 0;for(int j = 1 ; j <= i ; j ++){num += tree_n[j - 1] * tree_n[i - j];}tree_n.push_back(num);}         return tree_n[n];     }};int main(){Solution text;cout << "numTrees(3) : " << text.numTrees(3) << endl;cout << "numTrees(4) : " << text.numTrees(4) << endl;}




0 0