Unique Binary Search Trees
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
思路: f(n) = Σi=1n f(n-i)*f(i-1), 其中 f(0) = f(1) = 1; 利用动归记下之前的 f(2)~f(n-1)即可。
1 2 3 4 5 6 7 8 9 10 11 | class Solution { public : int numTrees( int n) { vector< int > f(n+1, 0); f[0] = f[1] = 1; for ( int v = 2; v <= n; ++v) for ( int pos = 1; pos <= v; ++pos) f[v] += f[pos-1] * f[v-pos]; return f[n]; } }; |
Unique Binary Search Trees II
Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.
For example, Given n = 3, your program should return all 5 unique BST's shown below.
1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
思路:分别以 1~n 为根节点,左右子树根的集合数量相乘,递归,依次得出结果。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ vector<TreeNode *> generateTreesCore( int start, int end) { vector<TreeNode *> vec; if (start > end) { vec.push_back(NULL); return vec; } for ( int cur = start; cur <= end; ++cur) { vector<TreeNode *> left = generateTreesCore(start, cur-1); vector<TreeNode *> right = generateTreesCore(cur+1, end); for ( size_t i = 0; i < left.size(); ++i) { for ( size_t j = 0; j < right.size(); ++j) { TreeNode *root = new TreeNode(cur); root->left = left[i]; root->right = right[j]; vec.push_back(root); } } } return vec; } class Solution { public : vector<TreeNode *> generateTrees( int n) { return generateTreesCore(1, n); } }; |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步