1.纯递归
(1)C++实现:
#include<bits/stdc++.h>
using namespace std;
static int num = 0;
int cut(int p[], int n) {
num++;
int q = -1;
if(n == 0) {
return 0;
}
for(int i = 0; i<n; i++ ) {
q = max(q, p[i] + cut(p,n-i-1));
}
return q;
}
int main(){
int n = 8;
int p[] = {1,5,8,9,10,17,17,20,24,30};
cout<<cut(p,n)<<endl;
cout<<num<<endl;
return 0;
}
int main(){
int n = 8;
int p[] = {1,5,8,9,10,17,17,20,24,30};
cout<<cut(p,n)<<endl;
cout<<num<<endl;
return 0;
}
(2)java实现:
public class 钢铁切割问题_纯递归 {
private static int []p = {1,5,8,9,10,17,17,20,24,30};
static int num = 0; //递归调用次数
public static void main(String[] args) {
// TODO Auto-generated method stub
int n = 10;
System.out.println(cut(p,n));
System.out.println(num);
}
public static int cut(int []p, int n) {
num ++;
int q = -1;
if(n == 0) {
return 0;
}
for(int i = 0; i<n; i++ ) {
q = Math.max(q, p[i] + cut(p,n-i-1));
}
return q;
}
}
public class 递归_动态规划 {
private static int []p = {1,5,8,9,10,17,17,20,24,30};
static int num = 0; //递归调用次数
public static void main(String[] args) {
// TODO Auto-generated method stub
int n = 10;
System.out.println(cut(p,n));
System.out.println(num);
System.out.println(bottom_up_cut(p, n));
}
// 自顶向下方法
public static int cut(int []p, int n) {
int []r = new int[n];
for(int i = 0; i<r.length; i++) {
r[i] = -1;
}
return memoized_cut(p, n, r);
}
public static int memoized_cut(int []p, int n, int []r) {
if(n >= 1 && r[n-1] > 0) {
return r[n];
}
int q = -1;
if(n == 0) {
q = 0;
}
else {
num++;
for(int i = 0; i<n; i++ ) {
q = Math.max(q, p[i] + cut(p,n-i-1));
}
}
if(n>=1) {
r[n-1] = q;
}
return q;
}
// 自底向上方法
public static int bottom_up_cut(int []p, int n) {
int []r = new int[n+1];
r[0] = 0; //长度为0的收益为0
// 依次求解规模为1,2···n的子问题
for(int i = 1; i < r.length; i++) {
int q = -1;
for(int j = 1 ; j <= i; j++) {
q = Math.max(q, p[j-1] + r[i-j]);
}
r[i] = q;
}
return r[r.length-1];
}
}
public class 动态规划_重构最优解 {
private static int []p = {1,5,8,9,10,17,18,20,24,30};
public static void main(String[] args) {
// TODO Auto-generated method stub
int n = 7;
System.out.println(bottom_up_cut(p, n));
}
// 自底向上方法
public static int bottom_up_cut(int []p, int n) {
int []r = new int[n+1];
int []s = new int[n+1];
r[0] = 0; //长度为0的收益为0
// 依次求解规模为1,2···n的子问题
for(int i = 1; i < r.length; i++) {
int q = -1;
for(int j = 1 ; j <= i; j++) {
if(q < p[j-1] + r[i-j]) {
q = p[j-1] + r[i-j];
s[i] = j; //保存最优解对应的第一段切割长度j
}
}
r[i] = q;
}
// 输出一个最优解
while(n > 0) {
System.out.print(s[n]+" ");
n = n - s[n];
}
return r[r.length-1];
}
}