剪绳子

本文深入探讨了《剑指Offer》中经典算法题目“剪绳子”的解决方案,通过数学推导,阐述了如何在给定长度的绳子上切割以获得最大乘积的策略。文章强调了当绳子长度超过4时,最佳切割方案应尽量将绳子切分为长度为3的段落,并详细解释了边界条件处理和具体实现方法。

 AcWing打卡活动

《剑指Offer》打卡活动 

周二第二题   剪绳子

/**
 * 1、设 ni >= 5, 3 * (ni - 3) >= ni? 2 * ni >= 9? 衡大于
 * 2、ni = 4 时, 拆分为2 * 2 才为最大
 * 3、2 * 2 * 2 < 3 * 3 故能拆分成3时,尽量拆分为三
 * 4、除了边界情况不得已才会拆分出1
 * 5、最大值为58, 59会溢出 -1970444362
 */
class Solution {
    public int maxProductAfterCutting(int length)
    {
        // 边界判断 当 2 <= length <= 3时,因为必须要拆除了一段
        if(length <= 3) return 1 * (length - 1);
        
        int res = 1;
        // 如果求余后,为4 ,则 为 2 * 2 的情况,成积为4
        if(length % 3 == 1) {
            res *= 4;
            length -= 4;
        } else if (length % 3 == 2) { // 如果秋雨后为2,则可以减去一个二
            res *= 2;
            length -= 2;
        }
        
        // 以上的if判断完成后,接下来都是3的倍数了,n个3相乘可确保最大
        while(length > 0) {
            res *= 3;
            length -= 3;
        }
        return res;
    }
}

 

### 贪心算法实现 贪心算法的思路是尽可能多地出长度为3的绳子段,因为当绳子长度大于等于5时,出长度为3的段可以获得更大的乘积。当剩下的长度为4时,将其成两个2的段,这样可以获得更大的乘积[^2]。 ```cpp #include <iostream> #include <cmath> class Solution { public: int cutRope(int number) { if(number < 2) return 0; if(number == 2) return 1; if(number == 3) return 2; int countOf3 = number / 3; if (number - countOf3 * 3 == 1) { countOf3--; return static_cast<int>(pow(3, countOf3)) * 4; } if (number - countOf3 * 3 == 2) { return static_cast<int>(pow(3, countOf3)) * 2; } return static_cast<int>(pow(3, countOf3)); } }; int main() { Solution sol; std::cout << sol.cutRope(10) << std::endl; // 输出 36 return 0; } ``` ### 动态规划实现 动态规划的思路是将绳子长度从1到n的所有可能法都计算出来,并存储在数组中。对于每个长度i,遍历所有可能的法j(从1到i-1),并计算j*(i-j)和dp[j]*(i-j)的乘积,取最大值作为dp[i]的值[^1]。 ```cpp #include <iostream> #include <vector> #include <algorithm> class Solution { public: int cutRope(int number) { if (number < 2) return 0; if (number == 2) return 1; if (number == 3) return 2; std::vector<int> dp(number + 1, 0); for (int i = 1; i <= number; ++i) { for (int j = 1; j < i; ++j) { dp[i] = std::max(dp[i], std::max(j * (i - j), j * dp[i - j])); } } return dp[number]; } }; int main() { Solution sol; std::cout << sol.cutRope(10) << std::endl; // 输出 36 return 0; } ``` ### 总结 - **贪心算法**:适用于较大的绳子长度,时间复杂度为O(1),但需要数学推导来证明最优解。 - **动态规划**:适用于较小的绳子长度,时间复杂度为O(n^2),但不需要数学推导。 两种方法都可以有效地解决绳子问题,选择哪种方法取决于具体的应用场景和对时间复杂度的要求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值