343. 整数拆分
数组表示一个集合,由于可能出现两个或多个相乘,所以递推的公式是 dp[i] = max(dp[i], j * dp[i-j]); dp[i] = max(dp[i], j * (i-j));
// dp[i] = dp[x] * dp[i-x]
class Solution {
public:
int integerBreak(int n) {
vector<int> dp(n + 1);
if (n == 2) return 1;
if (n == 3) return 2;
dp[1] = 1;
dp[2] = 1;
dp[3] = 2;
for (int i = 4; i <= n; i ++)
{
for (int j = 2; j <= i - 2; j ++)
{
dp[i] = max(dp[i], j * dp[i-j]);
dp[i] = max(dp[i], j * (i-j));
}
}
return dp[n];
}
};
96. 不同的二叉搜索树
这题比较难,我觉得再碰到也不会写。
class Solution {
public:
int numTrees(int n) {
vector<int>dp(n + 1);
dp[0] = 1;
for (int i = 1; i <= n; i ++)
for (int j = 1; j <= i; j ++)
dp[i] += dp[j-1] * dp[i-j];
return dp[n];
}
};