1.思路:
动态规划法:
package jianzhi_offer;
public class cut_shengzi {
public static void main(String[] args) {
// TODO Auto-generated method stub
int length = 3;
int result = matProductAfterCutting_1(length);
System.out.println(result);
}
private static int matProductAfterCutting_1(int length) {
if(length < 2) {
return 0;
}
if(length == 2) {
return 1;
}
if(length == 3) {
return 2;
}
//将最优解存储在数组中
int[] products = new int[length+1];
//数组中第i个元素表示把长度为i的绳子剪成若干段之后的乘积的最大值
products[0] = 0;
products[1] = 1;
products[2] = 2;
products[3] = 3;
int max = 0;
for(int i = 4; i <= length; i++) {
max = 0;
//求出所有可能的f(j)*f(i-j)并比较出他们的最大值
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];
return max;
}
}
贪心算法
package jianzhi_offer;
public class cut_shengzi_2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int length = 8;
int result = cutProp(length);
System.out.println(result);
}
public static int cutProp(int length) {
if(length < 2) {
return 0;
}
if(length == 2) {
return 1;
}
if(length == 3) {
return 2;
}
int timeOf_3 = length/3;
if(length - timeOf_3*3 == 1) {
timeOf_3-=timeOf_3;
}
int timeOf_2 = (length - timeOf_3*3)/2;
return (int)((Math.pow(3,timeOf_3))*(Math.pow(2,timeOf_2)));
}
}