剪绳子(Java实现)


public class E14CuttingRope {
    //切割绳子,使得分段长度乘积最大

    public static int maxResultsAfterCutting_Solution1(int length) {
        //基于动态规划
        if (length < 2)
            return -1;
        if (length == 3)
            return 2;
        //被切割成相应长度所得值
        int[] results = new int[length + 1];
        results[0] = 0;
        results[1] = 1;
        results[2] = 2;
        results[3] = 3;
        //至下而上计算最优值
        int max = 0;
        for (int i = 4; i <= length; i++) {
            for (int j = 1; j <= i / 2; j++) {
                results[i] = results[j] * results[i - j];
                if (max < results[i])
                    max = results[i];
            }
            results[i] = max;
        }
        return results[length];
    }

    public static int maxResultsAfterCutting_Solution2(int length){
        //基于贪心算法实现
        int maxThreeTimes = length / 3;
        //余数为1时,即出现最后一个数为4的情况
        if (length % 3 == 1)
            maxThreeTimes -= 1;

        int maxTwoTimes = (length - maxThreeTimes * 3) / 2;
        return  (int)Math.pow(3, maxThreeTimes) * (int)Math.pow(2, maxTwoTimes);
    }

    //测试用例
    public static void main(String[] args){
        System.out.println(E14CuttingRope.maxResultsAfterCutting_Solution1(4));
        System.out.println(E14CuttingRope.maxResultsAfterCutting_Solution1(5));
        System.out.println(E14CuttingRope.maxResultsAfterCutting_Solution2(4));
        System.out.println(E14CuttingRope.maxResultsAfterCutting_Solution2(5));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值