343. 整数拆分
这题用动态规划确实没想到
class Solution {
public int integerBreak(int n) {
int[] dp = new int[n + 1];
dp[2] = 1;
for(int i = 3;i <= n;i++){
for(int j = 1;j <= i/2;j++){
dp[i] = Math.max(dp[i],Math.max(j * (i - j),j * dp[i - j]));
}
}
return dp[n];
}
}
贪心算法:
class Solution {
public int integerBreak(int n) {
if(n == 2) return 1;
if(n == 3) return 2;
int result = 1;
if(n % 3 == 0){
while(n != 0){
result *= 3;
n = n - 3;
}
}else if(n % 3 == 1){
n = n - 4;
result *= 4;
while(n != 0){
result *= 3;
n = n - 3;
}
}else if(n % 3 == 2){
n = n - 2;
result *= 2;
while(n != 0){
result *= 3;
n = n - 3;
}
}
return result;
}
}
96.不同的二叉搜索树
dp[i]表示有i个元素的二叉搜索树
dp[i] += dp[j - 1]*dp[i - j];
初始值dp[0] = 1;
dp[1] = 1;
class Solution {
public int numTrees(int n) {
int[] dp = new int[n+1];
dp[0] = 1;
dp[1] = 1;
for(int i = 2;i <= n;i++){
//里层循环次数和数字n相同
for(int j = 1;j <= i;j++){
dp[i] += dp[j - 1] * dp[i - j];
}
}
return dp[n];
}
}