【发布时间】:2020-05-22 13:30:58
【问题描述】:
给定一棵大小为 N 的二叉树,找出其中最大独立集 (LIS) 的大小。如果子集的任何两个节点之间没有边,则所有树节点的子集是一个独立集。你的任务是完成函数 LISS(),它找到最大独立集的大小。
我想出了这个递归解决方案。
int rec(struct Node *root,bool t)
{
if(root==NULL)
return 0;
if(t==true)
{
return max(1+rec(root->left,!t)+rec(root->right,!t),rec(root->left,t)+rec(root->right,t));
}
else
{
return max(rec(root->left,!t)+rec(root->right,!t),rec(root->left,t)+rec(root->right,t));
}
}
int LISS(struct Node *root)
{
int x,y;
y=rec(root,true);
return y;
}
为了通过DP解决这个问题,我修改了代码如下,但是给出了错误的答案。 它甚至不适用于具有不同元素的二叉树。
map<int,int> mm;
int rec(struct Node *root,bool t)
{
if(root==NULL)
return 0;
if(mm.find(root->data)!=mm.end())
return mm[root->data];
if(t==true)
{
mm[root->data]=max(1+rec(root->left,!t)+rec(root->right,!t),rec(root->left,t)+rec(root->right,t));
return mm[root->data];
}else
{
mm[root->data]=max(rec(root->left,!t)+rec(root->right,!t),rec(root->left,t)+rec(root->right,t));
return mm[root-s>data];
}
}
int LISS(struct Node *root)
{
//Code here
mm={};
int y=0;
y=rec(root,true);
return max(x,y);
}
错在哪里?
【问题讨论】:
-
您尝试过什么调试问题?你被困在哪里了?
标签: recursion tree c++14 binary-tree dynamic-programming