Skip to content

Instantly share code, notes, and snippets.

@lyleaf
Last active August 19, 2016 13:25
Show Gist options
  • Save lyleaf/90aff9363c34d4a03244b7428ac2a9b2 to your computer and use it in GitHub Desktop.
Save lyleaf/90aff9363c34d4a03244b7428ac2a9b2 to your computer and use it in GitHub Desktop.
二叉搜索树的个数和枚举(DP)(vector copy)
/*My naive solution...only beats 0.6% of people...
因为..因为有好多numTrees(n)都重复算了...
所以把这个改成DP的话应该就可以加快不少时间
*/
class Solution {
public:
int numTrees(int n) {
int r = 0;
if (n==0) return 0;
if (n==1) return 1;
if (n==2) return 2;
for (int i=0;i<n-2;i++){
r += numTrees(n-i-2)*numTrees(i+1);
}
r += 2*numTrees(n-1);
return r;
}
};
class Solution {
public:
int numTrees(int n) {
vector<int> dp(n+1);
dp[0] = 1;
dp[1] = 1;
dp[2] = 2;
if (n==0) return 0;
if (n==1) return 1;
if (n==2) return 2;
for (int x=3;x<=n;x++){
for (int i=0;i<x;i++){
dp[x] += dp[x-1-i]*dp[i];
}
cout << dp[x] << " ";
}
return dp[n];
}
};
/*
如何把一个vector的值一个一个复制到一个新个vector里面?
*/
@lyleaf
Copy link
Author

lyleaf commented Aug 18, 2016

给你一个整数n,找出所有BST(Binary Search Trees)的个数。并枚举。BST是右子节点大于根,左子节点小于根。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment