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)即可。
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 为根节点,左右子树根的集合数量相乘,递归,依次得出结果。
/** * 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); } };