思路:
- 是用动态规划来进行解决
很简单,从长度等于2开始,肯定是1,赋初值
之后大于2的时候到n为止,在分段的时候j从2开始分段,到i-1为止,取最大值。
max(dp[i],max(j*(i-j),j*dp[i-j]))
class Solution {
public int cuttingRope(int n) {
//动态规划解决此题目:
int []dp=new int[n+1];
dp[2]=1; //分成两段
for(int i=3;i<=n;i++){
for(int j=2;j<i;j++){
dp[i]=Math.max(dp[i],Math.max(j*(i-j),j*dp[i-j]));
}
}
return dp[n];
}
}
2.使用贪心算法:
步骤如下:
如果 n == 2,返回1,如果 n == 3,返回2,两个可以合并成n小于4的时候返回n - 1
如果 n == 4,返回4
如果 n > 4,分成尽可能多的长度为3的小段,每次循环长度n减去3,乘积res乘以3;最后返回时乘以小于等于4的最后一小段
以上2和3可以合并
class Solution {
public int cuttingRope(int n) {
int res=1;
if(n<=3){
return n-1;
}
else if(n==4)
return 4;
else{
while(n>4){
res*=3;
n-=3;
}
return res*n;
}
}
}