73:Unique Binary Search Trees

来源:互联网 发布:spss数据分析 编辑:程序博客网 时间:2024/06/09 17:30

题目: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.
题目的具体形式 见 https://leetcode.com/problems/unique-binary-search-trees/?tab=Description

该题目的解法解法代码的思想及编写参考了网址https://github.com/soulmachine/leetcode#leetcode题解题目

代码如下:

// 时间复杂度 O(n^2),空间复杂度 O(n)class Solution {public:        int numTrees(int n) {                if (n <= 1) return 1;                // num[i] 表示能够存储 i 个连续排列数                // 的唯一 BSL 树的数目                vector<int> num(n + 1, 0);                num[0] = 1; // 表示不需要存储数,即空树                num[1] = 1; // 表示只需要存储一个数的树的数目                for (int i = 2; i <= n; ++i)                        for (int j = 1; j <= i; ++j)                                num[i] += num[j - 1] * num[i - j];                return num[n];        }};
0 0
原创粉丝点击