剑指offer第2版14题:剪绳子

小渣渣的算法学习笔记:2018秋招备战


数据结构类算法总结:动态规划 贪心算法


1.题目描述:

给你一根长度为n的绳子,请把绳子剪成m段,每段绳子长度即为k[0],k[1],.....k[m].
请问k[0]xk[1]x....xk[m]的最大乘积是多少?例如,当绳子长度是8时,我们把他剪成
长度分别为2,3,3的三段,此时得到最大乘积是18

2.代码实现:

public class Solution67_14 {
    public static void main(String[] args) {
        Solution67_14 s = new Solution67_14();
        int maxresult1 = s.maxCuttingRope1(4);
        int maxresult2 = s.maxCuttingRope2(4);
        System.out.println(maxresult1);
        System.out.println(maxresult2);
    }

    //解法1:动态规划
    public int maxCuttingRope1(int ropeLength){
        if(ropeLength < 2) return 0;
        if(ropeLength == 2) return 1;
        if(ropeLength == 3) return 2;

        int []results = new int[ropeLength+1];

        results[0] = 0;
        results[1] = 1;
        results[2] = 2;
        results[3] = 3;

        int max = 0;

        for(int i =4;i<=ropeLength;i++){
            max = 0;
            for(int j =1;j<=i/2;++j){
                int result = results[j]*results[i-j];
                if(max < result){
                    max = result;
                }
                results[i] = max;
            }
        }

        max = results[ropeLength];
        return max;
    }

    //解法2:贪婪算法
    public int maxCuttingRope2(int ropeLength){
        if(ropeLength <2) return 0;
        if(ropeLength == 2) return 1;
        if(ropeLength == 3) return 2;

        //尽可能多的剪去长度为3的绳子
        int timesOf3 = ropeLength /3;

        //当绳子最后剩下的长度为4的时候,不能再剪去长度为3的绳子
        //此时更好的方法是把绳子剪成长度为2的两段,2*2 > 1*3
        if(ropeLength - timesOf3 * 3 == 1){
            timesOf3 = timesOf3 -1;
        }
        int timesOf2 = (ropeLength -timesOf3*3)/2;

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

猜你喜欢

转载自blog.csdn.net/weixin_42561115/article/details/80920813