343. 整数拆分
动态规划法:
class Solution {
public int integerBreak(int n) {
int[] dp = new int[n+1];
if(n <= 3) {
return n - 1;
}
dp[0] = 0;
dp[1] = 1;
dp[2] = 2;
dp[3] = 3;
for(int i = 4; i < n + 1; ++i) {
int max = 0;
for(int j = 1; j < i/2 + 1; ++j) {
max = Math.max(max, dp[i-j]*dp[j]);
}
dp[i] = max;
}
return dp[n];
}
}
数学法(居然是自己想出来的):
class Solution {
public int integerBreak(int n) {
if(n <= 3) {
return n - 1;
}
if(n % 3 == 0) {
return (int)Math.pow(3, n/3);
}else if(n % 3 == 1) {
return (int)(4 * Math.pow(3, (n-4)/3));
}else {
return (int)(2 * Math.pow(3, (n-2)/3));
}
}
}
96.不同的二叉搜索树
题目链接:96. 不同的二叉搜索树 - 力扣(LeetCode)
class Solution {
public int numTrees(int n) {
int dp[] = new int[n + 1];
if(n <= 2) {
return n;
}
dp[0] = 1;
dp[1] = 1;
dp[2] = 2;
for(int i = 3; i < n+1; ++i) {
for(int j = 1; j <= i; ++j) {
dp[i] += dp[j-1] * dp[i -j];
}
}
return dp[n];
}
}