Day 41 动态规划
343. 整数拆分
class Solution {
public:
int integerBreak(int n) {
if (n == 2) return 1;
if (n == 3) return 2;
if (n == 4) return 4;
int a = 2, b = 3, c = 4;
for (int i = 5; i <= n; i++)
{
int tmp = max(b * 2, a * 3);
a = b;
b = c;
c = tmp;
}
return c;
}
};
96. 不同的二叉搜索树
这道题没回忆起来,稍微参考了一下答案
class Solution {
public:
int numTrees(int n) {
vector<int> table(n + 1, 0);
table[0] = 1;
for (int i = 1; i < table.size(); i++)
{
int sum = 0;
for (int j = 1; j <= i; j++)
{
sum += table[j - 1] * table[i - j];
}
table[i] = sum;
}
return table[n];
}
};