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)表示长度为n的二叉树有多少种结果,则
F(n) = F(0)*F(n-1) + F(1)*F(n-2) + F(2)*F(n-2) + ......+ F(n-1)*F(0)
所以代码如下:
class Solution {public: int numTrees(int n) { if(n <= 0) return 0; vector nums(n+1,0); nums[0] = 1; for(int i = 1; i<=n; i++){ for(int j = 1; j <=i ; j++){ nums[i] += nums[j-1]*nums[i-j]; } } return nums[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
同样沿用 I 的思路,利用分治思想
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: vectorgenerateTrees(int n) { if(n <=0) return vector (); return generateSubTrees(1,n); } vector generateSubTrees(int s,int e){ vector res; if(s > e){ res.push_back(NULL); return res; } for(int i = s; i <= e;i++ ){ vector left = generateSubTrees(s,i-1); vector right = generateSubTrees(i+1,e); for(auto l : left){ for(auto r : right){ TreeNode* root = new TreeNode(i); root->left = l; root->right = r; res.push_back(root); } } } return res; }};