public class E14CuttingRope {
//切割绳子,使得分段长度乘积最大
public static int maxResultsAfterCutting_Solution1(int length) {
//基于动态规划
if (length < 2)
return -1;
if (length == 3)
return 2;
//被切割成相应长度所得值
int[] results = new int[length + 1];
results[0] = 0;
results[1] = 1;
results[2] = 2;
results[3] = 3;
//至下而上计算最优值
int max = 0;
for (int i = 4; i <= length; i++) {
for (int j = 1; j <= i / 2; j++) {
results[i] = results[j] * results[i - j];
if (max < results[i])
max = results[i];
}
results[i] = max;
}
return results[length];
}
public static int maxResultsAfterCutting_Solution2(int length){
//基于贪心算法实现
int maxThreeTimes = length / 3;
//余数为1时,即出现最后一个数为4的情况
if (length % 3 == 1)
maxThreeTimes -= 1;
int maxTwoTimes = (length - maxThreeTimes * 3) / 2;
return (int)Math.pow(3, maxThreeTimes) * (int)Math.pow(2, maxTwoTimes);
}
//测试用例
public static void main(String[] args){
System.out.println(E14CuttingRope.maxResultsAfterCutting_Solution1(4));
System.out.println(E14CuttingRope.maxResultsAfterCutting_Solution1(5));
System.out.println(E14CuttingRope.maxResultsAfterCutting_Solution2(4));
System.out.println(E14CuttingRope.maxResultsAfterCutting_Solution2(5));
}
}
剪绳子(Java实现)
最新推荐文章于 2022-02-26 11:29:57 发布