[LeetCode]95. Unique Binary Search Trees II(DP,二叉树)
题目链接:https://leetcode.com/problems/unique-binary-search-trees-ii/#/description
题意:给n个点,求这n个点不同形态的二叉树。
dfs模拟,固定当前点的值,构造左右子树。在后序遍历的时候把这左右子树合并到当前子树下,更新答案就行。
再用个dp(i,j)维护数字i到j的不同树的种类就行了。
1 class Solution { 2 public: 3 vector<TreeNode*> dp[111][111]; 4 vector<TreeNode*> dfs(int s, int e) { 5 if(dp[s][e].size() != 0) return dp[s][e]; 6 if(s > e) return dp[s][e] = vector<TreeNode*>(1, NULL); 7 if(s == e) return dp[s][e] = vector<TreeNode*>(1, new TreeNode(s)); 8 vector<TreeNode*> ret; 9 for(int i = s; i <= e; i++) { 10 vector<TreeNode*> l, r; 11 l = dfs(s, i-1); 12 r = dfs(i+1, e); 13 for(int j = 0; j < l.size(); j++) { 14 for(int k = 0; k < r.size(); k++) { 15 TreeNode* p = new TreeNode(i); 16 p->left = l[j]; 17 p->right = r[k]; 18 ret.push_back(p); 19 } 20 } 21 } 22 return dp[s][e] = ret; 23 } 24 vector<TreeNode*> generateTrees(int n) { 25 for(int i = 0; i <= n; i++) { 26 for(int j = 0; j <= n; j++) { 27 dp[i][j].clear(); 28 } 29 } 30 if(n == 0) return vector<TreeNode*>(); 31 return dfs(1, n); 32 } 33 };