LeetCode 343. 整数拆分
力扣题目链接
正整数n,先拆成两个数i, n-i
,拆成多个数可以对n-i
进行拆分,然后对这些求最大值。
- 确定dp数组以及下标的含义:对i进行拆分的最大乘积
- 确定递归公式:
dp[i] = max(dp[i], j * (i - j), j * dp[i-j])
- dp数组如何初始化:
dp[0]=0, dp[1]=0, dp[2]=1
- 确定遍历顺序
- 举例推导dp数组
class Solution:
def integerBreak(self, n: int) -> int:
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[-1]
LeetCode 96.不同的二叉搜索树
class Solution:
def numTrees(self, n: int) -> int:
if n <= 1:
return 1
dp = [0] * (n + 1)
dp[0] = 1
dp[1] = 1
dp[2] = 2
for i in range(3, n+1):
for j in range(i):
dp[i] += dp[j] * dp[i-j-1]
return dp[-1]
今日毕!