枚举i从 2 到 n / 2 + 1
答案为 i * (n - i) 和 i * dfs(n - i)的最大值
class Solution:
def integerBreak(self, n: int) -> int:
if n == 1 or n == 2:
return 1
if n == 3:
return 2
dp = [0] * (n + 1)
dp[2] = 1
for i in range(3, n + 1):
for j in range(1, i // 2 + 1):
dp[i] = max(dp[i], j * (i - j), j * dp[i - j])
return dp[n]
记忆化搜索
class Solution:
@cache
def numTrees(self, n: int):
if n <= 1:
return 1
cnt = 0
for i in range(n):
cnt += self.numTrees(i) * self.numTrees(n - 1 - i)
return cnt
dp
class Solution:
def numTrees(self, n: int):
dp = [0] * (n + 1)
dp[0] = dp[1] = 1
for i in range(2, n + 1):
for j in range(1, i + 1):
dp[i] += dp[j - 1] * dp[i - j]
return dp[n]