本文来自于《算法导论》中动态规划学习笔记。
JAVA实现:
import java.util.Arrays; public class CutRod { public static void cutRod(int[] p, int n, int[] r, int[] s) { r[0] = 0; s[0] = 0; for (int i = 1; i <=n ; i++) { int q = Integer.MIN_VALUE; for (int j = 1; j <= i ; j++) { if (q < p[j] + r[i-j]) { q = p[j] + r[i-j]; s[i] = j; } } r[i] = q; } } public static void printCutSolution(int[] s, int n) { while (n > 0) { System.out.print(s[n] + " "); n -= s[n]; } } public static void main(String[] args) { int n = 10; int[] p = {0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30}; int[] r = new int[n+1]; int[] s = new int[n+1]; cutRod(p, n, r, s); System.out.println(Arrays.toString(r)); System.out.println(Arrays.toString(s)); printCutSolution(s, 7); } }