题目:给你一根长度为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(int length)
{
if(length < 2)
return 0;
int* products = new int[length + 1];
products[0] = 0;
products[1] = 1;
int max = 0;
for(int i = 2; i <= length; ++i)
{
max = 0;
for(int j = 1; j <= i / 2; ++j)
{
int product = products[j] * products[i - j];
if(max < product)
max = product;
products[i] = max;
}
}
max = products[length];
delete[] products;
return max;
}
记得删除创建的变量!!
贪心算法:
int maxProductAfterCutting(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));
}