一、题目
剪绳子:给你一根长度为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。
二、解法
我们有两种不同的方法解决这个问题,先用常规的需要O(n²)时间和O(n)空间的动态规划思路,接着用只需要O(1)的时间和空间的贪心算法。
2.1 动态规划
分析:首先定义函数f(n)为把长度为n的绳子剪成若干段后各段长度乘积的最大值。在剪第一刀的时候,我们有n-1中可能的选择,也就是剪出来的第一段绳子可能长度为1,2,...,n-1。因此f(n) = max(f(i) * f(n-i))。其中0<i<n。
#include <iostream> #include <cstdio> #include <string> #include <stack> using namespace std; int maxProductAfterCutting_Solution1(int length) { if (length < 2) return 0; if (length == 2) return 1; if (length == 3) return 2; int *products = new int[length + 1]; products[0] = 0; products[1] = 1; products[2] = 2; products[3] = 3; int max = 0; for (int i = 4; i <= length; ++i) { max = 0; for (int j = 1; j <= i / 2; j++) { int product = products[j] * products[i - j]; if (product > max) max = product; } products[i] = max; } max = products[length]; delete[] products; return max; } int main() { cout <<maxProductAfterCutting_Solution1(10)<<endl; system("pause"); }
2.2 贪心算法
如果我们按照如下的策略来剪绳子,则得到的各段绳子的长度的乘积将最大:当n≥5时,我们尽可能多的剪长度为3的绳子;当剩下的绳子长度为4时,把绳子剪成两段长度为2的绳子。
int maxProductAfterCutting_solution2(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)); }