zoukankan      html  css  js  c++  java
  • 剪绳子-动态规划-贪婪

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

    // ====================动态规划====================
    //四个特点;
    //求问题最优解
    //问题最优解可以分解为子问题的最优解
    //可以分解为具有重复的子问题
    //从上向下分析问题,从下向上计算问题

    int maxProductAfterCutting_solution1(int length)
    {
        if (length < 2)//当大小小于3的时候可以直接得出
            return 0;
        if (length == 2)
            return 1;
        if (length == 3)
            return 2;
    
        int* products = new int[length + 1];
        products[0] = 0;
        products[1] = 1;
        products[2] = 2;
        products[3] = 3;
    
        int max = 0;
        for (int i = 4; i <= length; ++i)
        {
            max = 0;
            for (int j = 1; j <= i / 2; ++j)
            {
                int product = products[j] * products[i - j];//products[j]和products[i - j]都是已经得到的
                if (max < product)
                    max = product;
    
                products[i] = max;//选择存起来每个子问题的最优解,提高效率
            }
        }
    
        max = products[length];
        delete[] products;
    
        return max;
    }

    2.贪婪 难一些

    // ====================贪婪算法====================
    //需要数学底子,比如下面这个就得公式证明3(n-3)>=2(n-2),n>=5。。
    
    int maxProductAfterCutting_solution2(int length)
    {
        if (length < 2)
            return 0;
        if (length == 2)
            return 1;
        if (length == 3)
            return 2;
    
        // 尽可能多地减去长度为3的绳子段
        int timesOf3 = length / 3;
    
        // 当绳子最后剩下的长度为4的时候,不能再剪去长度为3的绳子段。
        // 此时更好的方法是把绳子剪成长度为2的两段,因为2*2 > 3*1。
        if (length - timesOf3 * 3 == 1)
            timesOf3 -= 1;
    
        int timesOf2 = (length - timesOf3 * 3) / 2;
    
        return (int)(pow(3, timesOf3)) * (int)(pow(2, timesOf2));
    }
  • 相关阅读:
    js 字符串转化成数字:(实例:用正则检测大于0的正数,最多保留4位小数)
    SQL Server 2008 阻止保存要求重新创建表的更改问题的设置方法
    Entity Framework学习二:定义数据结构
    Entity Framework学习一:在.net类基础上创建新数据库
    Create Primary Key using Entity Framework Code First
    MVC缓存(转载)
    不错的博文地址
    read xml test
    xml读取类
    VS2010+ASP.NET MVC4+EF4+JqueryEasyUI+Oracle项目开发(转载)
  • 原文地址:https://www.cnblogs.com/cgy1012/p/11377362.html
Copyright © 2011-2022 走看看