从递归解决方案转换为DP时遇到问题

时间:2020-02-06 13:26:07

标签: recursion tree c++14 binary-tree dynamic-programming

给定大小为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);
}

怎么了?

1 个答案:

答案 0 :(得分:0)

函数中有两种状态,但是您仅记住一种状态。假设对于根x,

rec(x,true) = 5

rec(x,false) = 10

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

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