package DP;
import java.util.List;
public class _343_IntegerBreak {
// 1. 递归暴力解法
// F(n) = max{i * F(n-i)}, i = 1,2,3,4,5...n-1
public int helper1(int n) {
if (n == 2){
// 2 = 1+1, 1*1 = 1
return 1;
}
int res = Integer.MIN_VALUE;
for (int i = 1; i <= n - 1; i++){
// 获取当前每一个分支的最大值
int tmp = Math.max(i*(n - i), i*integerBreak(n-i));
// 和之前的最大值res进行比较和更新
res = Math.max(res, tmp);
System.out.println(tmp + ":" + res);
}
return res;
}
//2. 递归+记忆化
public int helper2(int n, int[] mem){
if (n == 2){
return 1;
}
if (mem[n] != 0){
return mem[n];
}
int res = Integer.MIN_VALUE;
for (int i = 1; i <= n - 1; i++){
// 获取当前每一个分支的最大值
int tmp = Math.max(i*(n - i), i*integerBreak(n-i));
// 和之前的最大值res进行比较和更新
res = Math.max(res, tmp);
}
mem[n] = res;
return res;
}
// 3. dp
/**
* 2 = 1+1, 1*1 = 1
* 3 = 1+1+1, 1*1*1 = 1
* 3 = 2 + 1, 2*1 = 2
*/
public int helper3(int n){
int[] dp = new int[n+1];
dp[2] = 1;
for (int i = 3; i <= n; i++){
for (int j = 1; j <= i-1; j++){
dp[i] = Math.max(dp[i], Math.max(j*(i-j), j*dp[i-j]));
}
}
return dp[n];
}
public int integerBreak(int n){
// return helper1(n);
// int[] mem = new int[n+1];
// return helper2(n, mem);
return helper3(n);
}
public static void main(String[] args) {
System.out.println(new _343_IntegerBreak().integerBreak(10));
}
}
Leetcode_343_IntegerBreak_分割整数的最大乘积
最新推荐文章于 2020-07-30 17:40:45 发布