// 面试题14:剪绳子
// 题目:给你一根长度为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。
思路:动态规划为了避免重复计算,所以从下往上运算,满足用动态规划的三个条件:
1.该问题是求一个问题的最优解
2.整体问题的最优解是依赖于各个子问题的最优解
3.这些小问题之间还有相互重叠的更小的问题
贪婪算法的特点:和动态规划不一样,该问题每一步都可以做出一个贪婪的选择,基于这个选择,我们确定能够
得到最优解。
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
using namespace std;
//动态规划求解
int maxProductAfterCutting_solution1(int length)
{
if (length < 2)
return 0;
if (length = 2)
return 1;
if (length = 3)
return 2;
int *product = new int[length+1];
product[0] = 0;
product[1] = 0;
product[2] = 2;
product[3] = 3;
int max = 0;
for (int i = 4; i <= length; ++i)
{
max = 0;
for (int j = 1; j <= 2 / i; ++j)
{
product[i] = product[j] * product[i - j];
if (product[i] > max)
max = product[i];
}
product[i] = max;
}
max = product[length];
delete[] product;
return max;
}
//贪婪算法求解
int maxProductAfterCutting_solution2(int length)
{
if (length < 2)
return 0;
if (length = 2)
return 1;
if (length = 3)
return 2;
int timesOf3 = length / 3;
if ((length - timesOf3 * 3) == 1)
{
timesOf3 -= 1;
// int timesOf2 = 2;
}
int timesOf2 = (length - timesOf3 * 3) / 2;
return ((int)pow(3, timesOf3)*(int)pow(2, timesOf2));
}
int main()
{
return 0;
}