Leetcode 题解 - Dynamic Programming 1D

题解

State: (n)

State(n): how many unique BST to form with n nodes from 1, n, where i is the selected root

for range 1, i -1, this is calculated range for unique BST

for rangei, n-i, this is the another range for unique BST

multiply the answer for above two ranges for final result

High Level:

  1. Initialize memo with n + 1 slots
  2. call dfs(n)

dfs(n):

  1. Base case (n <= 1) -> return 1
  2. If memon != null -> return memon
  3. Ask subproblems for answers:

a. for i in 1,n:

i. left = dfs(i-1), right = dfs(n-i)

ii. result = left * right

  1. Update memon and return result

时间复杂度:O(n**2)

另可以用正向填表:把dfs的flow反过来,从底层子问题开始往大计算,最终计算到顶层问题

High Level

  1. Initialize memon + 1
  2. Fill out base case -> memo0 = memo1 = 1
  3. for i in 2,n:

a. Use Transition Rule -> for j in 1, i:

i. memoi += memoj-1 * memoi - j

  1. return memon

时间复杂度:O(n**2)

思路

High Level

  1. Initialize memo

  2. Call dfs(s,n)

dfs(s,n)

  1. Base case -> n <= 1 return 1
  2. If memon != null -> return memon
  3. Ask Subproblems for answers

a. if x is valid (not 0) -> result += memon-1

b. if xx is valid (<= 26) -> result += memon-2

  1. Update memo and return result
相关推荐
装不满的克莱因瓶2 分钟前
【从零搭建】AI大模型之ReactAgent智能体对接MCP实战
java·人工智能·ai·springai·mcp·springaialibaba
kyle~36 分钟前
因子图优化(Factor Graph Optimization)
c++·算法·机器人·传感器
SimonKing1 小时前
AI Assistant被"隐藏"了?别慌,IDEA 2026.3 这波是换了个脑子
java·后端·程序员
Resean02231 小时前
SpringMVC 6+源码分析(九)异常处理
java·spring·springmvc
geats人山人海1 小时前
现代c++4.1
java·开发语言·c++
Pniubi2 小时前
贪心算法入门
算法·贪心算法
MobotStone2 小时前
AI 能不能越用越会用?从“改答案”到“改进自己”,读懂 RSI
人工智能·算法
下一站春风里2 小时前
Spring IoC 控制反转 完整技术笔记
java·spring boot·笔记·spring
挖掘狂人2 小时前
用户连点两次「确认支付」,你的后端凭什么只扣一次钱?
java·后端·面试
codigger2 小时前
用户连点两次「确认支付」,你的后端凭什么只扣一次钱?
java·程序员·支付·java后端