343整数拆分
https://leetcode.cn/problems/integer-break/
容易错的地方是i分成j & i - j两段,一段不切,一段可切可不切(不切时不被dp包含需要单独拿出来比大)
class Solution {
public int integerBreak(int n) {
int[] dp = new int[n + 1]; // dp值由于k>=2是至少切一刀
dp[1] = 1;
for (int i = 2; i <= n; i++) {
for (int j = 1; j < i; j++) {
dp[i] = Math.max(dp[i], Math.max(dp[j], j) * (i - j)); // bug, 左边大段可切可不切
}
}
return dp[n];
}
}
96不同的二叉搜索树
https://leetcode.cn/problems/unique-binary-search-trees/
class Solution {
public int numTrees(int n) {
int[] dp = new int[n + 1];
dp[0] = 1;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) { //1-i, 以j为根
dp[i] += dp[j - 1] * dp[i - j];
}
}
return dp[n];
}
}