ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

剑指offer 面试题14:剪绳子 java

2019-05-10 11:53:57  阅读:220  来源: 互联网

标签:面试题 return 14 int 绳子 len products timeOfThree java


题目:

给你一根长度为n的绳子,请把绳子剪成m段,记每段绳子长度为k[0],
k[1]...k[m-1],求k[0]k[1]...k[m-1]的最大值。已知绳子长度n为整数
,m>1(至少要剪一刀,不能不剪),k[0],k[1]...k[m-1]均要求为整数。
例如,绳子长度为8时,把它剪成3-3-2,得到最大乘积18;绳子长度
为3时,把它剪成2-1,得到最大乘积2。

动态规划解法:

public class MaxProductAfterCutting {
    public static void main(String args[]) {
        int cutting = getMaxProductAfterCutting(3);
        System.out.println(cutting);
    }

    private static int getMaxProductAfterCutting(int len) {
        int max = 0;
        if (len < 2)
            return 0;
        if (len == 2)
            return 1;
        if (len == 3)
            return 2;
        //存储长度从 0-len 的最大结果
        int[] products = new int[len + 1];// 将最优解存储在数组中
        // 数组中第i个元素表示把长度为i的绳子剪成若干段之后的乘积的最大值
        products[0] = 0;
        products[1] = 1;
        products[2] = 2;
        products[3] = 3;
        //自底向上开始求解
        for (int i = 4; i <= len; i++) { //i表示长度
            for (int j = 1; j <= len / 2; j++) {//由于长度i存在(1,i-1)和(i-1,1)的重复,所以只需要考虑前一种
                int product = products[j] * products[i - j];
                if (max < product)
                    max = product;
            }
            products[i] = max;
        }
        max = products[len];
        return max;
    }
}

贪心算法

public static int maxProductWithGreedy(int len) {
        if (len < 2)
            return 0;
        if (len == 2)
            return 1;
        if (len == 3)
            return 2;
        //啥也不管,先尽可能减去长度为3的段
        int timeOfThree = len / 3;

        //判断还剩下多少,再进行处理
        if (len - timeOfThree * 3 == 1)
            timeOfThree -= 1;
        int timeOfTwo = (len - timeOfThree * 3) / 2;

        return (int) ((Math.pow(3, timeOfThree)) * (Math.pow(2, timeOfTwo)));
    }

标签:面试题,return,14,int,绳子,len,products,timeOfThree,java
来源: https://blog.csdn.net/Qyuewei/article/details/90054764

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有