题目: 给你一根长度为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_solution1(int length)
{
if (length < 2)
return 0;
if (length == 2)
return 1;
if (length == 3)
return 2;
int* products = (int*)malloc((length + 1)*sizeof(int));
assert(products != NULL);
memset(products, 0, (length + 1)*sizeof(int));
/****长度为0、1、2、3的绳子的长度********/
products[0] = 0;
products[1] = 1;
products[2] = 2;
products[3] = 3;
int max = 0;
int i = 0;
int j = 0;
for (i = 4; i <= length; i++)
{
max = 0;
for (j = 1; j <= i / 2; j++)
{
int product = products[j] * products[i - j];
if (max < product)
max = product;
products[i] = max;
}
}
max = products[length];
free(products);
products = NULL;
return max;
}
products[0] = 0;
products[1] = 1;
products[2] = 2;
products[3] = 3;
为什么 products[2] = 2;products[3] = 3;呢?因为n=2,3不能再分了。