这道题分成两道,一道是不考虑答案取模,一道考虑取模。
题目描述
1. 题目一
给你一根长度为 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。
示例 1:
输入: 2
输出: 1
解释: 2 = 1 + 1, 1 × 1 = 1
示例 2:
输入: 10
输出: 36
解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36
提示:
2 <= n <= 58
2. 题目二
在题目一的基础上,答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。
解题思路(题目一)
首先对于题目一,不考虑答案取模。有两种实现方法:动态规划和贪婪算法。
1. 动态规划
首先定义函数product(n),含义是把一条长度为n的绳子切成若干整数段,其每段长度乘积的最大值。在切第一刀的时候有n-1种可能的切法,可以将绳子切为长度为i和(n-i)的两部分,因此可得product(n)=max{product(n-i)*product(i)}。
这是一个由上向下的递归公式,而若想得到product(n)的值,必须先得到product(i)和product(n-i)的值,因此在计算时应自下而上地进行。也就是说,先得到product(4)、product(5)…、product(n-1),最后才能得到product(n)。
另外,product函数的前几个值可以事先推出。例如,当绳子长度为2时,由于至少剪一刀,因此最大乘积为1。以此类推,绳子长度为3时,最大乘积为2;绳子长度小于2时,最大乘积为0。而如果绳子长度大于3,此时就不一定对长度为3的这部分绳子剪一刀了,因此其最大乘积与前面推出的不等。也就是说,应首先判断绳子长度n的大小,若n<=3,则直接返回至少剪一刀的结果;若n>3,则先对product(0)~product(3)分别赋值为0 ~ 3,再对n>3的部分进行动态规划计算。
动态规划算法的时间复杂度O(n^2),空间复杂度O(n)。
代码
class Solution {
public int cuttingRope(int n) {
if(n<2)
return 0;
if(n==2)
return 1;
if(n==3)
return 2;
int[] product = new int[n+1];
product[0] = 0;
product[1] = 1;
product[2] = 2;
product[3] = 3;
for(int i=4; i<=n; i++){
int max = 0;
for(int j=1; j<=i/2; j++){
int pro = product[j]*product[i-j];
if(max<pro)
max = pro;
}
product[i] = max;
}
return product[n];
}
}
2. 贪婪算法
先说结论:对于n>=5的绳子,尽可能多剪长度为3的绳子;当剩下的绳子长度为4时,把绳子剪成长度为2的两段绳子。
证明以上结论的正确性:
首先对于n>=5:
有(n-3)*3>n,且(n-2)*2>n;
又有(n-3)*3 >= (n-2)*2。
因此应把绳子尽可能多地剪为长度为3的绳子。
当n==4时,由于2 * 2 > 1 * 3,因此应把绳子剪为长度为2的两段绳子。
证毕。
代码就按照以上思路写,贪婪算法的时间复杂度和空间复杂度都为O(1)。
class Solution {
public int cuttingRope(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);
}
}
解题思路(题目二)
题目二要求对答案取模,因此不能用动态规划,因为取模之后无法用max函数来比较大小了。
因此用贪婪算法,尽可能多地剪成长度为3的绳子,同时对当前乘积取模1e9+7(1000000007)。要注意最后结果乘n(n是<=4的部分,就不切了)。
代码
class Solution {
public int cuttingRope(int n) {
if(n<=3)
return n-1;
long res = 1;
int mod = (int)1e9+7;
while(n>4){
res *= 3;
n -= 3;
res %= mod;
}
return (int)(res*n%mod);
}
}