剑指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)); } }
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- 【剑指offer】剪绳子 -- Python 实现
- 剑指Offer-14:剪绳子
- 剑指offer----015(剪绳子)
- 【Golang】LeetCode-剑指Offer-面试题14- I-剪绳子【两种写法】
- 剑指offer--面试题14:剪绳子
- 剑指 offer第14题-剪绳子
- 【剑指offer】第十四题(剪绳子) 和 第十五题(二进制中的数)
- 剑指Offer面试题14:剪绳子 Java代码实现
- [剑指Offer] 14_剪绳子
- 剑指offer-动态规划-剪绳子问题分析
- 剑指offer 剪绳子
- java 剪绳子 剑指offer
- 剑指Offer 面试题14 剪绳子
- 【剑指offer】面试题14:剪绳子
- 【剑指offer】面试题28:字符串的排列
- 剑指Offer——归并排序思想应用
- 【剑指offer】数值的整数次方
- 剑指Offer——回溯算法解迷宫问题(java版)
- <剑指offer 面试题6-2>从尾到头打印链表 Java
- 剑指Offer面试题34:丑数 Java实现