// 面试题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。 #include <iostream>
#include <cmath> // ====================动态规划====================
int maxProductAfterCutting_solution1(int length)
{
if(length < )
return ;
if(length == )
return ;
if(length == )
return ; int* products = new int[length + ];
products[] = ;
products[] = ;
products[] = ;
products[] = ; int max = ;
for(int i = ; i <= length; ++i)
{
max = ;
for(int j = ; j <= i / ; ++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_solution2(int length)
{
if(length < )
return ;
if(length == )
return ;
if(length == )
return ; // 尽可能多地减去长度为3的绳子段
int timesOf3 = length / ; // 当绳子最后剩下的长度为4的时候,不能再剪去长度为3的绳子段。
// 此时更好的方法是把绳子剪成长度为2的两段,因为2*2 > 3*1。
if(length - timesOf3 * == )
timesOf3 -= ; int timesOf2 = (length - timesOf3 * ) / ; return (int) (pow(, timesOf3)) * (int) (pow(, timesOf2));
} // ====================测试代码====================
void test(const char* testName, int length, int expected)
{
int result1 = maxProductAfterCutting_solution1(length);
if(result1 == expected)
std::cout << "Solution1 for " << testName << " passed." << std::endl;
else
std::cout << "Solution1 for " << testName << " FAILED." << std::endl; int result2 = maxProductAfterCutting_solution2(length);
if(result2 == expected)
std::cout << "Solution2 for " << testName << " passed." << std::endl;
else
std::cout << "Solution2 for " << testName << " FAILED." << std::endl;
} void test1()
{
int length = ;
int expected = ;
test("test1", length, expected);
} void test2()
{
int length = ;
int expected = ;
test("test2", length, expected);
} void test3()
{
int length = ;
int expected = ;
test("test3", length, expected);
} void test4()
{
int length = ;
int expected = ;
test("test4", length, expected);
} void test5()
{
int length = ;
int expected = ;
test("test5", length, expected);
} void test6()
{
int length = ;
int expected = ;
test("test6", length, expected);
} void test7()
{
int length = ;
int expected = ;
test("test7", length, expected);
} void test8()
{
int length = ;
int expected = ;
test("test8", length, expected);
} void test9()
{
int length = ;
int expected = ;
test("test9", length, expected);
} void test10()
{
int length = ;
int expected = ;
test("test10", length, expected);
} void test11()
{
int length = ;
int expected = ;
test("test11", length, expected);
} int main(int agrc, char* argv[])
{
test1();
test2();
test3();
test4();
test5();
test6();
test7();
test8();
test9();
test10();
test11(); return ;
}
05-07 15:50