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
相关推荐
天天向上2911 分钟前
Spring AI 实战:14 个踩坑记录,其中一个让我的测试全绿但产品是坏的
java·开源
正在走向自律10 分钟前
从只写接口到独立交付前后端,飞算JavaAI能给Java后端工程师多少溢价?
java·springboot·ai编程·全栈开发·java求职·飞算javaai·金九银十
Chen—LSN29 分钟前
C语言——文件操作(2)
c语言·开发语言·c++·经验分享·笔记·算法·c#
多喝水身体棒41 分钟前
Spring Boot 自动配置原理,看完终于不慌了
面试·程序员
a努力。42 分钟前
LangChain Agent消息链路全解析
java·前端·javascript
SL_staff1 小时前
物模型是设备的数字身份证:属性、事件、服务如何决定IoT系统扩展性
java·物联网·全栈
程序员yu1 小时前
会编网络:别被入门教程骗了,Python实用能力不在语法本身
开发语言·python·学习·算法
资深技术分享员1 小时前
Geejing WebBuilder 日志、在线用户、系统监控,出问题时的三个第一现场
java·运维·数据库
卓怡学长1 小时前
w202springboot基于B_S架构的图书信息管理系统
java·spring boot·spring·intellij-idea
走到天涯海角1 小时前
用springBoot写几个简单的接口
java·spring boot·intellij-idea