package sort;
public class Test14 {
public static void main(String[] args) {
System.out.println(cut(8));
}
public static int cut(int a) {
int[] store = new int[a + 1];
if (a == 0)
return 0;
if (a == 1)
return 0; // 不符合规律,直接手动定义
if (a == 2)
return 1;
if (a == 3)
return 2;
for (int i = 0; i <= a; i++) {
if (i == 0)
store[i] = 0; // 利用数值存储已经计算过的,方便后来者进行计算
if (i == 1)
store[i] = 1;
if (i == 2)
store[i] = 2;
if (i == 3)
store[i] = 3;
if (i >= 4) { //如果大于大于4,则开始利用前面数组进行计算
//例如4可以分成1+3,2+2,求出最大值放入数组4位置
int max = 0;
for (int j = 1; j <= i / 2; j++) {
if (store[j] * store[i - j] > max)
max = store[j] * store[i - j];
}
store[i] = max;
}
}
return store[a];
}
}
本文介绍了一种使用动态规划算法解决物品切割问题的方法。通过预计算并存储子问题的解,避免了重复计算,显著提高了算法效率。文章详细展示了如何初始化数组、递归公式以及最终结果的获取。
596

被折叠的 条评论
为什么被折叠?



