您的位置:首页 > Web前端

剑指offer--剪绳子

2020-03-11 12:45 393 查看

题目描述:给你一根长度为n的绳子,请把绳子剪成m段(m,n均为正数且均大于1)每段绳子的长度之间乘积,最大乘积为多少?
思路:动态规划

//剪绳子,求最大乘机 8=2+3+3(2*3*3=18)
package Function;
//products[0]=0,products[1]=1,products[2]=2,products[3]=3,
//我的理解是,当length=4时,那么products[4]=products[1]*products[3]或者products[4]=products[2]*products[2]。
//动态规划
public class CutRope14 {
//绳子长度
public int cutRope(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;
//products[4]=products[1]*products[3]
// 或者products[4]=products[2]*products[2]
for (int i = 4; i <= length; i++) {
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];
return max;
}
public static void main(String[] args) {
CutRope14 rope = new CutRope14();
System.out.println(rope.cutRope(8));
}

}
  • 点赞
  • 收藏
  • 分享
  • 文章举报
LuckyAsYou 发布了49 篇原创文章 · 获赞 2 · 访问量 1206 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: