/**
* 剪绳子-I : https://leetcode-cn.com/problems/jian-sheng-zi-lcof/
* 动态规划
* @Description
*/
public class Test12 {
//动态规划
public int cuttingRope1(int n) {
if (n < 2){
return 0;
}
if (n == 2){
return 1;
}
if (n == 3){
return 2;
}
int[] products = new int[n + 1];
products[0] = 0;
products[1] = 1;
products[2] = 2;
products[3] = 3;
int max = 0;
for (int i = 4; i <= n ; i++) {
max = 0;
for (int j = 1; j <= i / 2 ; j++) {
int product = products[j] * products[i-j];
if (max < product){
max = product;
}
products[i] = max;
}
}
return products[n];
}
//贪心算法
public int cuttingRope(int n) {
if (n < 2)return 0;
if (n == 2)return 1;
if (n == 3)return 2;
int times3 = n / 3;
if (n - times3 * 3 == 1){
times3 -= 1;
}
int times2 = (n - times3*3) / 2;
return (int)(Math.pow(3,times3)) * (int)(Math.pow(2,times2));
}
public static void main(String[] args) {
System.out.println(new Test12().cuttingRope(50));
}
}
11-07
11-07