题解 | #剪绳子#
剪绳子
http://www.nowcoder.com/practice/57d85990ba5b440ab888fc72b0751bf8
分析题目: 一个数乘积最大就是求有多少个2、多少个3
动态规划求解
public int cutRope(int target) {
if(target == 2)return 1;
int[] dp = new int[target+1];//i数的最大值为dp[i]
dp[0]=0;dp[1]=1;dp[2]=2;dp[3]=3;
for(int i = 4; i<=target;i++)dp[i] = Math.max(dp[i-2]*2,dp[i-3]*3);
return dp[target];
}
模拟求解
public class Solution {
public int cutRope(int target) {
int sum = 1;
while(target>0){
if(target%3==0){
sum*=3;
target-=3;
} else {
sum*=2;
target-=2;
}
}
return sum;
}
}