剪绳子

// 面试题14:剪绳子
    // 题目:给你一根长度为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。
    // ====================动态规划====================
    static uint32_t max_product(uint32_t length)
    {
        if(length < 2)
            return 0;
        if(length == 2)
            return 1;
        if(length == 3)
            return 2;

        std::vector<uint32_t> products(length + 1, 0);
        products[0] = 0;
        products[1] = 1;
        products[2] = 2;
        products[3] = 3;

        uint32_t max = 0;
        for(uint32_t i = 4; i <= length; ++i)
        {
            max = 0;
            for(uint32_t j = 1; j <= i / 2; ++j)
            {
                uint32_t product = products[j] * products[i - j];
                if(max < product)
                {
                    max = product;
                }
            }
            products[i] = max;
        }

        return  products[length];
    }

    // ====================贪婪算法====================
    static uint32_t max_product2(uint32_t length)
    {
        if(length < 2)
            return 0;
        if(length == 2)
            return 1;
        if(length == 3)
            return 2;

        // 尽可能多地减去长度为3的绳子段
        uint32_t timesOf3 = length / 3;

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

        uint32_t timesOf2 = (length - timesOf3 * 3) / 2;

        return (uint32_t) (pow(3, timesOf3)) * (uint32_t) (pow(2, timesOf2));
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值