1.自顶向下求解

public class 钢条切割问题_自顶向下 {

public static int MEMOIZED_CUT_ROD(int []p,int n){
int [] r = new int [n +1];//记录不同长度的最优解
for (int i = 0;i<=n;i++){
r[i] = -1;//初始化最优解
}

return MEMOIZED_CUT_ROD_AUX(p,n,r);
}
public static int MEMOIZED_CUT_ROD_AUX(int []p,int n,int[]r){
int q;//存储最优解的值

if(r[n] >=0){
return r[n];
}
if (n == 0){
q = 0;
}else{
q = -1;
for (int i = 1; i<=n;i++){
q = Math.max(q ,p[i] + MEMOIZED_CUT_ROD_AUX(p,n-i,r));
}
}
r[n] = q;
return q;
}

public static void main(String[] args) {
// TODO Auto-generated method stub
int [] p = {0,1,5,8,9,10,17,17,20,24,30};//价格表，下标代表钢条长度
int n = 9;
int max = MEMOIZED_CUT_ROD(p, n);
System.out.print("长度为" + n + "的钢条最切割所得利润为：" + max);
}

}

2.自底向上求解

public class 钢条切割问题_自底向上 {

public static int BOTTOM_UP_CUT_POD(int []p,int n){
int [] r = new  int[n+1];
r[0] = 0;
int q;
for (int j = 1;j<=n;j++){
q = -1;
for (int i = 1;i<=j;i++){
q = Math.max(q, p[i] + r[j -i]);
}
r[j] = q;
}
return r[n];
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] p = {0,1,5,8,9,10,17,17,20,24,30};//价格表，下标代表钢条长度
int n = 9;
int max =BOTTOM_UP_CUT_POD(p, n);
System.out.print("长度为" + n + "的钢条最切割所得利润为：" + max);
}

}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120