1.动态规划
使用条件:问题能够分解成若干个子问题,并且子问题之间还有重叠的更小的子问题,就可以考虑使用动态规划来解决这个问题。
特点:
- 求一个问题的最优解;
- 整体问题的最优解是依赖各个子问题的最优解;
- 大问题分解成若干个小问题,这些小问题之间还有相互重叠的更小的子问题;
- 从上往下分析问题,从下往上求解问题。
1.1 剪绳子
需要O(n2)的时间复杂度和O(n)空间复杂度
public class CuttingSolution {
public static int maxProductCutting(int length) {
if (length < 2) return 0;
if (length == 2) return 1;
if (length == 3) return 2;
int[] products = new int[length + 1]; //存储子问题的最优解
products[0] = 0;
products[1] = 1;
products[2] = 2;
products[3] = 3;
int max = 0;
for (int i = 4; i <= length; i++) { //计算自下而上
max = 0;
for (int j = 0; j <= i / 2; j++) {
int product = products[j] * products[i - j];
if (max < product) max = product;
}
products[i] = max;
}
max = products[length];
return max;
}
public static void main(String[] args) {
System.out.println(maxProductCutting(5));
}
}
2. 贪婪算法
贪婪算法和动态规划的问题不一样。当我们应用贪婪算法解决问题的时候,每一步都可以做出一个贪婪的选择,基于这个选择,我们确定能够得到最优解。
2.1 剪绳子
需要O(1)的时间复杂度和O(1)空间复杂度
public class CuttingSolution2 {
public static int maxProductCutting(int length) {
if (length < 2) return 0;
if (length == 2) return 1;
if (length == 3) return 2;
int a = length / 3;
int b = length % 3;
if (b == 0) return (int) Math.pow(3, a);
if (b == 1) return (int) (Math.pow(3, a - 1) * 4);
return (int) Math.pow(3, a) * 2;
}
public static void main(String[] args) {
System.out.println(maxProductCutting(8));
}
}