动态规划、贪婪算法、剪绳子

1.动态规划

使用条件:问题能够分解成若干个子问题,并且子问题之间还有重叠的更小的子问题,就可以考虑使用动态规划来解决这个问题。

特点:

  1. 求一个问题的最优解;
  2. 整体问题的最优解是依赖各个子问题的最优解;
  3. 大问题分解成若干个小问题,这些小问题之间还有相互重叠的更小的子问题;
  4. 从上往下分析问题,从下往上求解问题。
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));
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值