【问题标题】:Having problem in conversion from Recursive solution to DP从递归解决方案转换为 DP 时遇到问题
【发布时间】: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


【解决方案1】:

您的函数中有两种状态,但您只记住一种状态。假设根 x,

rec(x,true) = 5

rec(x,false) = 10.

您首先计算了rec(x, true),并将其保存在地图“mm”中为 mm[x] = 5。

因此,当您尝试获取 rec(x, false) 的值时,它会获取 rec(x, true) 的值,即 5。

【讨论】:

    猜你喜欢
    • 2014-08-20
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    • 2020-08-09
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多