剪繩子(動態規劃及貪心法)

int maxProductAfterCutting_solution(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(max<product)
max=product;
products[i]=max;
}
}
max=products[length];
delete []products;
return max;
}io

int maxProductAfterCutting_solution2(int length){//貪心法當n>=5時儘量多的剪長度爲3的繩子,當n=4時剪成兩段長度爲二的繩子
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 = (length-timesof3*3)/2;
return (int)(pow(3,timesof3))*(int)(pow(2,timesof2));im

}time

相關文章
相關標籤/搜索