记忆棒切割算法

时间:2014-05-01 19:57:56

标签: java algorithm dynamic-programming

我正在尝试实现memoized版本的递归杆切割算法。这是我的代码(我是用Cormen的伪代码实现的)

public class simpleMemoized {

    //finds maximum of two given integers
    public static int max(int a, int b) {
        return (a > b) ? a : b;

    }

    public static int MemoizedCutRod(int price, int lenght) {

        int[] r = new int[lenght + 1];
        for (int i = 1; i <= lenght; i++) {
            r[i] = 0;
        }
        return MemoizedCutRodAux(price, lenght, r);
    }

    public static int MemoizedCutRodAux(int price, int lenght, int[] r) {

        int[] priceTable = new int[11];
        priceTable[1] = 1;
        priceTable[2] = 5;
        priceTable[3] = 8;
        priceTable[4] = 9;
        priceTable[5] = 10;
        priceTable[6] = 17;
        priceTable[7] = 17;
        priceTable[8] = 20;
        priceTable[9] = 24;
        priceTable[10] = 30;

        if (r[lenght] >= 0) {
            return r[lenght];
        }

        if (lenght == 0) {
            return 0;
        }
        int q = 0;

        for (int i = 1; i <= lenght; i++) {
            q = max(q, priceTable[i] + MemoizedCutRodAux(price, lenght, r));
            r[lenght] = q;
        }
        return q;
    }

此代码的所有输出均为0.但此代码的非记忆版本正在运行。它有什么问题?这是工作代码:

public class Simple {

    //finds maximum of two given integers
    public static int max(int a, int b) {
        return (a > b) ? a : b;

    }

    public static int cormenCutRod(int price, int lenght) {

        int[] priceTable = new int[11];
        priceTable[1] = 1;
        priceTable[2] = 5;
        priceTable[3] = 8;
        priceTable[4] = 9;
        priceTable[5] = 10;
        priceTable[6] = 17;
        priceTable[7] = 17;
        priceTable[8] = 20;
        priceTable[9] = 24;
        priceTable[10] = 30;

        if (lenght == 0) {
            return 0;
        }
        int q = 0;
        for (int i = 1; i <= lenght; i++) {
            q = max(q, priceTable[i] + cormenCutRod(price, lenght - i));
        }

        return q;
    }

1 个答案:

答案 0 :(得分:0)

这应该有用。

static int cutRodM(int lenght)
    {

        int[] priceTable = new int[11];
        priceTable[1] = 1;
        priceTable[2] = 5;
        priceTable[3] = 8;
        priceTable[4] = 9;
        priceTable[5] = 10;
        priceTable[6] = 17;
        priceTable[7] = 17;
        priceTable[8] = 20;
        priceTable[9] = 24;
        priceTable[10] = 30;

       int[] mem= new int[lenght+1];
       mem[0] = 0;
       int i, j;
      //filling the table bottom up 
       for (i = 1; i<=lenght; i++)
       {
           int q = 0;
           for (j = 1; j <= i; j++)
             q = max(q, priceTable[j] + mem[i-j]);
           mem[i] = q;
       }

       return mem[lenght];
    }

Ideone链接:http://ideone.com/OWgrAZ