zoukankan      html  css  js  c++  java
  • 剪绳子(剑指offer_14)

    题目描述


    把一根绳子剪成多段,并且使得每段的长度乘积最大。


    n = 2 return 1 (2 = 1 + 1) n = 10 return 36 (10 = 3 + 3 + 4)
    
    
    贪心
    尽可能多剪长度为3的绳子,并且不允许有长度为1的绳子出现。如果出现了,就从已经切好长度为3的绳子中拿出一段与长度为1的绳子重新组合,把他们切成两段长度为2的绳子。
    public int integerBreak(int n) {
        if (n < 2)
            return 0;
        if (n == 2)
            return 1;
        if (n == 3)
            return 2;
        int timesOf3 = n / 3;
        if (n - timesOf3 * 3 == 1)
            timesOf3--;
        int timesOf2 = (n - timesOf3 * 3) / 2;
        return (int) (Math.pow(3, timesOf3)) * (int) (Math.pow(2, timesOf2));
    }
    
    

    动态规划

    public int integerBreak(int n) {
        int[] dp = new int[n + 1];
        dp[1] = 1;
        for (int i = 2; i <= n; i++)
            for (int j = 1; j < i; j++)
                dp[i] = Math.max(dp[i], Math.max(j * (i - j), dp[j] * (i - j)));
        return dp[n];
    }
    
    


  • 相关阅读:
    Easy-Transfer学习
    录音+语音转文字
    pyQt点击事件和数据传输
    第一个python-ui界面
    python写第一个网页
    pyhthon第一个小脚本——文件备份
    Stones HDU 1896
    Cow Sorting POJ 3270 & HDU 2838
    Stones
    大数相加
  • 原文地址:https://www.cnblogs.com/ziytong/p/12107366.html
Copyright © 2011-2022 走看看