剑指offer剪绳子java实现

本文探讨了如何使用动态规划和贪婪算法解决实际问题,通过实例演示了如何计算给定长度绳子最有效的切割方式。作者提供了`cuttingRope`和`cuttingRope1`两个方法,分别展示了这两种算法在20和5长度绳子切割中的应用。
摘要由CSDN通过智能技术生成

会陆续把之前刷的题都慢慢传上来
动态规划和贪婪算法
package com.hzp.action;

public class CuttingRope {
//动态规划
public static int cuttingRope(int length) {
if(length<2) {
return 0;
}
if(length2) {
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++) {
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(length
3) {
return 2;
}
//尽可能剪长度为3的绳子段
int timeOf3=length/3;
//当剩下最后4时,不能再-3了,2x2更大
if(length-timeOf3
3==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));
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值