会陆续把之前刷的题都慢慢传上来
动态规划和贪婪算法
package com.hzp.action;
public class CuttingRope {
//动态规划
public static int cuttingRope(int length) {
if(length<2) {
return 0;
}
if(length2) {
return 1;
}
if(length3) {
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++) {
for(int j=1;j<=i/2;j++) {
products[i]=products[j]products[i-j];
if(max<products[i]) {
max=products[i];
}
products[i]=max;
}
}
return products[length];
}
//̰贪婪算法
public static int cuttingRope1(int length) {
if(length<2) {
return 0;
}
if(length2) {
return 1;
}
if(length3) {
return 2;
}
//尽可能剪长度为3的绳子段
int timeOf3=length/3;
//当剩下最后4时,不能再-3了,2x2更大
if(length-timeOf33==1) {
timeOf3–;
}
int timeOf2=(length-timeOf33)/2;
return (int)Math.pow(3, timeOf3)(int)Math.pow(2, timeOf2);
}
public static void main(String[] args) {
CuttingRope c=new CuttingRope();
System.out.println(c.cuttingRope(20));
System.out.println(c.cuttingRope1(5));
}
}