class Solution { public int cuttingRope(int n) { int[] dp = new int[n+1]; dp[1] = 1; dp[2] = 1; for(int i = 3;i<=n;i++){ int x1 = i/2; int x2 = i - x1; int result = Math.max(x1,dp[x1])*Math.max(x2,dp[x2]); while(x1>2){ x1--; x2++; result = Math.max(result,Math.max(x1,dp[x1])*Math.max(x2,dp[x2])); } dp[i] = result; } return dp[n]; } }
动态规划
贪婪算法
每次剪出长度为3的绳子,当长度为4时,剪成长度为2和2的绳子。
public int cuttingRope(int n) { if(n<2) return 0; if(n == 2) return 1; if(n == 3) return 2; int times_of_3 = n/3; if(n%3 == 1){ times_of_3 --; } int times_of_2 = (n-times_of_3*3)/2; return (int)(Math.pow(3,times_of_3)*Math.pow(2,times_of_2)); }