剑指offer算法题:剪绳子

题目描述
给你一根长度为n的绳子,请把绳子剪成整数长的m段(m、n都是整数,n>1并且m>1),每段绳子的长度记为k[0],k[1],…,k[m]。请问k[0]xk[1]x…xk[m]可能的最大乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18。
输入描述:
输入一个数n,意义见题面。(2 <= n <= 60)

动态规划:

public class Solution {
    public int cutRope(int target) {
        if(target <= 2)
            return target == 2 ? 1 : 0;
        if(target == 3)
            return 2;
        int[] arr = new int[target + 1];
        arr[0] = 0;
        arr[1] = 1;
        arr[2] = 2;
        arr[3] = 3;
        int max;
        for(int i = 4;i <= target;i++) {
            max = 0;
            for(int j = 1;j <= i / 2;j++) {
                int cur = arr[j] * arr[i - j];
                max = Math.max(cur,max);
            }
            arr[i] = max;
        }
        return arr[target];
    }
}

贪婪算法:

public class Solution {
    public int cutRope(int target) {
        if(target <= 2)
            return target == 2 ? 1 : 0;
        if(target == 3)
            return 2;
        int timeOf3 = target / 3;
        //1 * 3 < 2 * 2,所以将1 + 3换为2 + 2
        if(target - (timeOf3 * 3) == 1)
            timeOf3 -= 1;
        int timeOf2 = (target - (timeOf3 * 3)) / 2;
        return (int) (Math.pow(3,timeOf3) * Math.pow(2,timeOf2));
    }
}
发布了239 篇原创文章 · 获赞 70 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43777983/article/details/104121732