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 range[i, 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 memo[n] != null -> return memo[n]
  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 memo[n] and return result

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

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

High Level

  1. Initialize memo[n + 1]
  2. Fill out base case -> memo[0] = memo[1] = 1
  3. for i in [2,n]:

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

i. memo[i] += memo[j-1] * memo[i - j]

  1. return memo[n]

时间复杂度: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 memo[n] != null -> return memo[n]
  3. Ask Subproblems for answers

a. if x is valid (not 0) -> result += memo[n-1]

b. if xx is valid (<= 26) -> result += memo[n-2]

  1. Update memo and return result
相关推荐
wearegogog1234 小时前
基于 MATLAB 的卡尔曼滤波器实现,用于消除噪声并估算信号
前端·算法·matlab
韩师学子--小倪4 小时前
fastjson与gson的toString差异
java·json
一只小小汤圆4 小时前
几何算法库
算法
Drawing stars4 小时前
JAVA后端 前端 大模型应用 学习路线
java·前端·学习
Evand J5 小时前
【2026课题推荐】DOA定位——MUSIC算法进行多传感器协同目标定位。附MATLAB例程运行结果
开发语言·算法·matlab
nbsaas-boot5 小时前
SQL Server 存储过程开发规范(公司内部模板)
java·服务器·数据库
行百里er5 小时前
用 ThreadLocal + Deque 打造一个“线程专属的调用栈” —— Spring Insight 的上下文管理术
java·后端·架构
leo__5205 小时前
基于MATLAB的交互式多模型跟踪算法(IMM)实现
人工智能·算法·matlab
忆锦紫5 小时前
图像增强算法:Gamma映射算法及MATLAB实现
开发语言·算法·matlab
玄〤5 小时前
黑马点评中 VoucherOrderServiceImpl 实现类中的一人一单实现解析(单机部署)
java·数据库·redis·笔记·后端·mybatis·springboot