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
相关推荐
刀法如飞4 小时前
AI时代:DDD领域驱动建模与Ontology语义建模的区别
java·设计模式·架构
jeffer_liu4 小时前
Spring AI 生产级实战:工具调用
java·人工智能·后端·spring·ai编程
比昨天多敲两行4 小时前
linux 线程概念与控制
java·开发语言·jvm
8Qi84 小时前
LeetCode 75:颜色分类(荷兰国旗问题)—— Java 题解 ✅
java·算法·leetcode·指针·排序
zzhongcy4 小时前
@Transactional 同类内部调用失效 + 两种自代理解决方案
java
Cosolar5 小时前
AutoGen 精通教程:从零到企业级多 Agent 系统架构师
人工智能·后端·面试
AutumnWind04205 小时前
【Intelij IDEA使用手册】
java·ide·intellij-idea
888CC++5 小时前
如何在 C 语言中进行程序调试?
前端·javascript·算法
就叫_这个吧6 小时前
Java注解、元注解、自定义注解定义及应用
java·开发语言·注解