memoization in C++

memoization in C++

本文关键字:C++ in memoization      更新时间:2023-10-16

给定板球球队的分数,查找/打印所有配置/方法来获得分数。有 3 种方法可以得分 2、3 和 7

例:成绩: 10

输出:(0,1,1)(0,2,2)(0,0,5)

void out(int score, int two, int three, int seven)
{
    if(score == 0)
    {
        cout << "(" << two << ", " << three << ", " << seven <<  ")" << endl;
    }
    else if (score < 0)
    {
        return;
    }
    else
    {
        outputs(score - 7, two, three, seven + 1);
        outputs(score - 3, two, three + 1, seven);
        outputs(score - 2, two + 1, three, seven);        
    }
    return;
}

确实得到了正确的答案,但重复并且还想使用记忆,我真的很困惑如何实现(0, 1, 1)(0, 1, 1)(2, 2, 0)(2, 2, 0)(2, 2, 0)(2, 2, 0)(2, 2, 0)(2, 2, 0)(5, 0, 0)

为了避免重复,您需要强制排序,例如,如果您以前使用分数3,则不允许使用分数7

void out(int score, int two, int three, int seven, int maxscore)
{
    ...
    else {
        if (maxscore >= 7) output(score-7, two, three, seven+1, 7);
        if (maxscore >= 3) output(score-3, two, three+1, seven, 3);
        if (maxscore >= 2) output(score-2, two+1, three, seven, 2);
    }
}

在这个问题上,使用记忆会更复杂(甚至可能不是那么有用),因为你正在寻找枚举所有解决方案(而不仅仅是计算它们)。

记忆的想法是保留一个表以避免重新计算相同的子问题。在这种情况下,子问题由分数和允许您使用的最大分数定义,但是解决方案还需要考虑您已经使用了多少个二三和七,如果您也将它们添加到键中,那么每个键将只访问一次(所以尝试记住它没有意义)。

如果您只需要计算可以达到分数的多少种不同方式,情况就不同了,因为在这种情况下,子问题的解决方案只是一个数字,您可以使用它来解决原始问题。