package undone;
public class t343 {
public static void main(String[] args) {
t343 t = new t343();
Solution solution = t.new Solution();
System.out.println(solution.integerBreak1(15));
}
class Solution {
/**
* @desc 贪心算法,尽量的把一个数拆为2的和,需要注意的是如果剩余的是3,那么不需要再拆
* @param n
* @return
*/
public int integerBreak0(int n) {
if(n <= 3) {
return n - 1;
}
int result = 1;
while ( n > 0) {
if(n < 3 || n == 4) {
result *= n;
break;
}
n -= 3;
result *= 3;
}
return result;
}
/**
* @desc 动态规划算法
* @param n
* @return
*/
public int integerBreak1(int n) {
if(n <= 3) {
return n-1;
}
int[] dp = new int[n+1];
dp[1] = 1;
dp[2] = 2;
dp[3] = 3;
for(int i = 4; i <= n; i++) {
dp[i] = Math.max(dp[i-2] * 2, dp[i-3] * 3);
}
return dp[n];
}
}
}
leetcode 343 整数拆分
最新推荐文章于 2023-05-14 00:20:29 发布