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
相关推荐
wabs6665 分钟前
关于动态规划【力扣1143.最长公共子序列的思考】
算法·leetcode·动态规划
码兄科技20 分钟前
Java AI智能体开发实战:从零构建企业级智能应用指南
java·开发语言·人工智能
2401_8595062424 分钟前
AIGC赋能大漆摆件设计:从痛点分析到技术架构与实战验证
java·大数据·人工智能
剑挑星河月26 分钟前
54.螺旋矩阵
java·算法·leetcode·矩阵
Robot_Nav1 小时前
MPPI 局部规划器实验设计讲解
人工智能·算法·mppi
Lhappy嘻嘻1 小时前
Java 并发编程(六)|并发进阶高频:CAS、锁升级
java·开发语言
mingo_敏1 小时前
Mean-Teacher 均值教师自训练框架详解
算法·均值算法
要开心吖ZSH1 小时前
MVCC 进阶:快照读 vs 当前读、幻读与 Next-Key Lock
java·数据库·sql·mysql·mvcc
京韵养生记2 小时前
【无标题】
java·服务器·前端
水木流年追梦2 小时前
agent面试必备31- AI Agent 核心进阶:工具路由(Tool Routing)
数据库·人工智能·oracle·面试·职场和发展·embedding