标签:
Title:
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
class Solution { public: int numTrees(int n) { vector<int> v(n+1,0); v[0] = 1; v[1] = 1; for (int i = 2; i <= n; i++){ for (int k = 0; k < i; k++){ v[i] += v[k] * v[i-1-k]; } } return v[n]; } };
Title:
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
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
/** * 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: vector<TreeNode*> generateTrees(int n) { return fun(1,n); } vector<TreeNode*> fun(int min,int max){ vector<TreeNode*> ret; if (min > max){ ret.push_back(NULL); return ret; } for(int i = min; i <= max; i++){ vector<TreeNode*> left = fun(min,i-1); vector<TreeNode*> right = fun(i+1, max); for (int m = 0; m < left.size(); m++){ for(int n = 0; n <right.size(); n++){ TreeNode * root = new TreeNode(i); root->left = left[m]; root->right = right[n]; ret.push_back(root); } } } } };
LeetCode: Unique Binary Search Trees I & II
标签:
原文地址:http://www.cnblogs.com/yxzfscg/p/4492756.html