14- II. 剪绳子 II


comments: true
difficulty: 中等
edit_url: https://github.com/doocs/leetcode/edit/main/lcof/%E9%9D%A2%E8%AF%95%E9%A2%9814-%20II.%20%E5%89%AA%E7%BB%B3%E5%AD%90%20II/README.md

面试题 14- II. 剪绳子 II

题目描述

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

答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。

 

示例 1:

输入: 2
输出: 1
解释: 2 = 1 + 1, 1 × 1 = 1

示例 2:

输入: 10
输出: 36
解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36

 

提示:

  • 2 <= n <= 1000

注意:本题与主站 343 题相同:https://leetcode.cn/problems/integer-break/

解法

方法一:数学(快速幂)

n < 4 n \lt 4 n<4,此时 n n n 不能拆分成至少两个正整数的和,因此 n − 1 n - 1 n1 是最大乘积。当 n ≥ 4 n \ge 4 n4 时,我们尽可能多地拆分 3 3 3,当剩下的最后一段为 4 4 4 时,我们将其拆分为 2 + 2 2 + 2 2+2,这样乘积最大。

时间复杂度 O ( log ⁡ n ) O(\log n) O(logn),空间复杂度 O ( 1 ) O(1) O(1)

Python3
class Solution:
    def cuttingRope(self, n: int) -> int:
        mod = 10**9 + 7
        if n < 4:
            return n - 1
        if n % 3 == 0:
            return pow(3, n // 3, mod)
        if n % 3 == 1:
            return (pow(3, n // 3 - 1, mod) * 4) % mod
        return pow(3, n // 3, mod) * 2 % mod
Java
class Solution {
    private final int mod = (int) 1e9 + 7;

    public int cuttingRope(int n) {
        if (n < 4) {
            return n - 1;
        }
        if (n % 3 == 0) {
            return qpow(3, n / 3);
        }
        if (n % 3 == 1) {
            return (int) (4L * qpow(3, n / 3 - 1) % mod);
        }
        return 2 * qpow(3, n / 3) % mod;
    }

    private int qpow(long a, long n) {
        long ans = 1;
        for (; n > 0; n >>= 1) {
            if ((n & 1) == 1) {
                ans = ans * a % mod;
            }
            a = a * a % mod;
        }
        return (int) ans;
    }
}
C++
class Solution {
public:
    int cuttingRope(int n) {
        if (n < 4) {
            return n - 1;
        }
        const int mod = 1e9 + 7;
        auto qpow = [&](long long a, long long n) {
            long long ans = 1;
            for (; n; n >>= 1) {
                if (n & 1) {
                    ans = ans * a % mod;
                }
                a = a * a % mod;
            }
            return (int) ans;
        };
        if (n % 3 == 0) {
            return qpow(3, n / 3);
        }
        if (n % 3 == 1) {
            return qpow(3, n / 3 - 1) * 4L % mod;
        }
        return qpow(3, n / 3) * 2 % mod;
    }
};
Go
func cuttingRope(n int) int {
	if n < 4 {
		return n - 1
	}
	const mod = 1e9 + 7
	qpow := func(a, n int) int {
		ans := 1
		for ; n > 0; n >>= 1 {
			if n&1 == 1 {
				ans = ans * a % mod
			}
			a = a * a % mod
		}
		return ans
	}
	if n%3 == 0 {
		return qpow(3, n/3)
	}
	if n%3 == 1 {
		return qpow(3, n/3-1) * 4 % mod
	}
	return qpow(3, n/3) * 2 % mod
}
Rust
impl Solution {
    pub fn cutting_rope(mut n: i32) -> i32 {
        if n < 4 {
            return n - 1;
        }
        let mut res = 1i64;
        while n > 4 {
            res = (res * 3) % 1000000007;
            n -= 3;
        }
        ((res * (n as i64)) % 1000000007) as i32
    }
}
JavaScript
/**
 * @param {number} n
 * @return {number}
 */
var cuttingRope = function (n) {
    if (n < 4) {
        return n - 1;
    }
    const mod = 1e9 + 7;
    const qpow = (a, n) => {
        let ans = 1;
        for (; n; n >>= 1) {
            if (n & 1) {
                ans = Number((BigInt(ans) * BigInt(a)) % BigInt(mod));
            }
            a = Number((BigInt(a) * BigInt(a)) % BigInt(mod));
        }
        return ans;
    };
    const k = Math.floor(n / 3);
    if (n % 3 === 0) {
        return qpow(3, k);
    }
    if (n % 3 === 1) {
        return (4 * qpow(3, k - 1)) % mod;
    }
    return (2 * qpow(3, k)) % mod;
};
C#
public class Solution {
    public int CuttingRope(int n) {
        if (n < 4) {
            return n - 1;
        }
        int res = 1;
        while (n > 4) {
            res *= 3;
            n -= 3;
        }
        if (n == 4) {
            return (res << 2) % 1000000007;
        }
        return (res * n) % 1000000007;
    }
}
Swift
class Solution {
    private let mod = 1000000007

    func cuttingRope(_ n: Int) -> Int {
        if n < 4 {
            return n - 1
        }
        if n % 3 == 0 {
            return qpow(3, n / 3)
        }
        if n % 3 == 1 {
            return (4 * qpow(3, n / 3 - 1)) % mod
        }
        return (2 * qpow(3, n / 3)) % mod
    }

    private func qpow(_ a: Int, _ n: Int) -> Int {
        var a = a
        var n = n
        var ans: Int = 1
        while n > 0 {
            if (n & 1) == 1 {
                ans = (ans * a) % mod
            }
            a = (a * a) % mod
            n >>= 1
        }
        return ans
    }
}
在C++中,绳子问题是一个经典的动态规划问题。问题描述为:给定一根长度为n的绳子,要求将其成m段(m>1),每段绳子的长度记为k, k, ..., k[m-1],请问如何绳子使得各段绳子的乘积最大? 解决这个问题的一种常见方法是使用动态规划。具体步骤如下: 1. 定义一个数组dp,其中dp[i]表示长度为i的绳子成若干段后各段绳子长度乘积的最大值。 2. 初始化dp数组,dp和dp都为0,因为长度为0和1的绳子无法断。 3. 从长度为2开始遍历到n,对于每个长度i,计算dp[i]的值。 - 遍历j从1到i-1,表示第一段绳子的长度,可以取值范围为1到i-1。 - 计算第一段绳子长度为j时,剩余绳子的长度为i-j。 - 计算当前情况下的乘积,即j * dp[i-j]。 - 更新dp[i]的值为所有情况中乘积最大的值。 4. 最终dp[n]即为所求的结果,表示长度为n的绳子成若干段后各段绳子长度乘积的最大值。 下面是绳子问题的C++代码示例: ```cpp #include <iostream> #include <vector> using namespace std; int cutRope(int n) { if (n <= 1) { return 0; } vector<int> dp(n + 1, 0); for (int i = 2; i <= n; i++) { for (int j = 1; j < i; j++) { dp[i] = max(dp[i], max(j * (i - j), j * dp[i - j])); } } return dp[n]; } int main() { int n = 8; int result = cutRope(n); cout << "将长度为" << n << "的绳子成若干段后各段绳子长度乘积的最大值为:" << result << endl; return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值