给你一根长度为n的绳子,请把绳子剪成整数长的m段(m、n都是整数,n>1并且m>1),每段绳子的长度记为k[0],k[1],...,k[m]。请问k[0]xk[1]x...xk[m]可能的最大乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18。
贪婪算法:
class Solution {
public:
int cutRope(int number) {
if( number < 2 ) return 0;
if( number == 2 ) return 1;
if( number == 3 ) return 2;
int timesOf3 = number/3;
if( number - 3 * timesOf3 == 1 ) {
timesOf3 -= 1;
}
int timesOf2 = (number - 3 * timesOf3)/2;
int res = pow( 3, timesOf3 ) *pow( 2, timesOf2 );
return res;
}
};
动态规划
class Solution {
public:
int cutRope(int number) {
if( number < 2 ) return 0;
if( number == 2 ) return 1;
if( number == 3 ) return 2;
int* products = new int[ number + 1 ];
products[ 0 ] = 0;
products[ 1 ] = 1;
products[ 2 ] = 2;
products[ 3 ] = 3;
int res = 0;
for ( int i = 4; i <= number; i ++ ) {
for( int j = 1 ;j <= i / 2; j++ ) {
res = max( res, products[j] * products[i - j] ) ;
}
products[i] = res;
}
return products[number];
}
};