描述
给你一根长度为n的绳子,请把绳子剪成整数长的m段(m、n都是整数,n>1并且m>1,m<=n),每段绳子的长度记为k[1],…,k[m]。请问k[1]x…xk[m]可能的最大乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18。
输入描述:
输入一个数n,意义见题面。(2 <= n <= 60)
示例1
输入:8
返回值:18
分析
数据量很小,直接枚举所有情况,把已经算好的中间结果存起来可以减少重复运算。
代码
public class Solution {
private int[] res = new int[65];
private int maxResult(int x){
if(res[x]>0) return res[x];
int ans = 4;
for(int i = 2;i<=x/2;i++){
int j = x-i;
int tem = maxResult(i)*maxResult(j);
if(tem > ans)
ans = tem;
}
res[x] = ans;
return ans;
}
public int cutRope(int target) {
if(target == 2) return 1;
if(target == 3) return 2;
res[2] = 2;
res[3] = 3;
return maxResult(target);
}
}