动态规划刷题
1、leetcode96 不同的二叉搜索树
描述:给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种?
思路:
-
就是利用二叉树的性质 根节点选定i之后 那么它的左子树的结点个数应该是 i -1;右子树的结点的个数应该是 n-i;
-
它是个和的形式 因为它有i个分配方式;左右子树的根节点数目不一样 对应不同的情况;
那么 它就应该累加起来;
那么 递推式子: f(x)+=f(x-1)*f(n-x)
class Solution {
public:
int numTrees(int n)
{
if(n==0)
return 1;
vector<int>dp(n+1,0);
dp[0]=1;//注意dp[0]=1;也是一种方案;
dp[1]=1;
for(int i=2;i<=n;i++)
for(int j=0;j<=i;j++)
dp[i]=dp[j-1]*dp[i-j];
return dp[n];
}
};
2、leetcode 95 不同二叉搜索树的输出
##### 思路:
-
一个二叉树的构造 从起始位置到终止位置进行构造;
设置一个辅助函数 从vector<TreeNode *>helper(int start,int end);来表示从start到end来构造二叉树结果放在容器中;
-
index从start 到end进行遍历;每一次结果压入result中
-
然后当前结点的左子树的结合 和右子树的集合
-
从集合中不断的取出一对左右子节点 (双层循环)来构造出一个二叉搜索树;
/**
* 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 {
private:
vector<TreeNode *>result;
vector<TreeNode*> helper(int start,int end)
{
vector<TreeNode *>res;
if(start==end)
res.push_back(new TreeNode(start));
else if(start>end)
res.push_back(nullptr);
else
{
for(int index=start;index<=end;index++)
{
vector<TreeNode *>left_union=helper(start,index-1);//构建左子树的集合
vector<TreeNode *>right_union=helper(index+1,end);//构建右子树的集合;
for(int i=0;i<left_union.size();i++)//双层循环遍历 找出不同的左右子树进行匹配构建的二叉搜索树;
for(int j=0;j<right_union.size();j++)
{
TreeNode *root=new TreeNode(index);
root->left=left_union[i];
root->right=right_union[j];
res.push_back(root);
}
}
}
return res;
}
public:
vector<TreeNode*> generateTrees(int n)
{
if(n==0)
return result;
return helper(1,n);
}
};