gpt4 book ai didi

java - 内存棒切割算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:23:35 26 4
gpt4 key购买 nike

我正在尝试实现递归棒切割算法的内存版本。这是我的代码(我从 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;
}

最佳答案

这应该有效。

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

关于java - 内存棒切割算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23415561/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com