[Leetcode][BST][Unique Binary Search Trees I & II]
根据定义写,不难,但是面试的时候需要用英语很快把思路说清楚,而且写出来没有BUG的代码,这样的要求只能之前不停的刷无数遍才能达到吧,好忧伤,感觉要找不到工作了。。。。。不开心。。。
1、输出所有树
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<TreeNode*> generate(int left, int right) { 13 vector<TreeNode*> nodes; 14 if (left > right) { 15 nodes.push_back(NULL); 16 return nodes; 17 } 18 for (int i = left; i <= right; i++) { 19 vector<TreeNode*> leftNodes = generate(left, i - 1); 20 vector<TreeNode*> rightNodes = generate(i + 1, right); 21 for (int a = 0; a < leftNodes.size(); a++) { 22 for (int b = 0; b < rightNodes.size(); b++) { 23 TreeNode *root = new TreeNode(i); 24 root->left = leftNodes[a]; 25 root->right = rightNodes[b]; 26 nodes.push_back(root); 27 } 28 } 29 } 30 return nodes; 31 } 32 vector<TreeNode *> generateTrees(int n) { 33 return generate(1, n); 34 } 35 };
指针的使用忘记了一些细节,还是要不停的刷题才可以呀!!加油!!
2、输出解的个数,直接用上面的方法会超时,要用DP的思路去思考 。
递推公式很简单,dp[i] = sum{dp[j] * dp[i - 1 - j]}。
1 class Solution { 2 public: 3 int numTrees(int n) { 4 vector<int> f(n + 1, 0); 5 f[0] = 1; 6 f[1] = 1; 7 f[2] = 2; 8 for (int i = 3; i <= n; i++) { 9 for (int k = 0; k < i; k++) { 10 f[i] += f[k] * f[i - k - 1]; 11 } 12 } 13 f[0] = 0; 14 return f[n]; 15 } 16 };