14:剪绳子

给你一根长度为n的绳子,把绳子剪成m段(m、n都是整数,m>1,n>1),每段绳子长度记为k[0],k[1],…,k[m]。请问k[0]k[1]…*k[m]可能的最大乘积是多少?例如,当绳子长度是8时,我们把它剪成长度分别为2,3,3的三段,此时得到的最大长度是18。

public class CuttingRope {
    //动态规划
    public int maxProduceAfterCutting_solution1(int length){
        if (length < 2)
            return 0;
        if (length == 2)
            return 1;
        if (length == 3)
            return 2;

        int[] products = new int[length + 1];//用于存放最大乘积值(最优解)
        //数组products[i]中第i个元素表示把长度为i的绳子剪成若干段之后最大乘积值
        products[0] = 0;
        products[1] = 1;
        products[2] = 2;
        products[3] = 3;

        int max;
        for (int i = 4; i <=  length; i++) {//i表示长度
            max = 0;
            //由于存在(i,i-1)与(i-1,i)的的重复,所以只需要考虑一种即可
            for (int j = 1; j <= i/2; j++) {
                int product = products[j] * products[i - j];
                if (max < product)
                    max = product;
            }
            products[i] = max;
        }
        return products[length];
    }

    //贪婪算法
    public int maxProduceAfterCutting_solution2(int length){
    	//把绳子剪成m段(m>1)即绳子至少要剪一次
        if (length < 2)
            return 0;//若绳子长度length=1,将绳子剪成0与1,乘积为1
        if (length == 2)
            return 1;
        if (length == 3)
            return 2;
		//尽可能多地去剪长度为3的绳子段
        int timesOf3 = length/3;
		//当绳子最后长度为4时,不能再剪长度为3的绳子段,而是剪成两段长度为2的绳子段
        if (length - timesOf3*3 == 1)
            timesOf3 -= 1;

        int timesOf2 = (length - timesOf3*3)/2;

        return (int) ((Math.pow(3, timesOf3))*(Math.pow(2, timesOf2)));
    }

    public void test(int length){
        System.out.println(" 动态规划: "+"绳子长度为"+length+"时,最大乘积 = "+maxProduceAfterCutting_solution1(length));
        System.out.println(" 贪婪算法: "+"绳子长度为"+length+"时,最大乘积 = "+maxProduceAfterCutting_solution2(length));
    }
	public static void main(String[] args) {
        CuttingRope cr = new CuttingRope();
        cr.test( 0);
        cr.test( 1);
        cr.test( 2);
        cr.test( 3);
        cr.test( 4);
        cr.test( 5);
        cr.test( 8);
        cr.test( 10);
        cr.test( 50);
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值