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 分钟前
w266基于spring boot + vue 圣地延安美食乐享系统
java·数据库·vue.js·spring boot·spring·intellij-idea
C++、Java和Python的菜鸟26 分钟前
第7章 Java高级技术
java·开发语言
程序员佳佳36 分钟前
模型网关灰度不是调百分比:把放量、观测和回滚做成账本
java·数据库·人工智能·redis·gpt·aigc·embedding
可靠的仙人掌43 分钟前
SAC(Soft Actor-Critic)算法底座
开发语言·算法·php
Listen·Rain2 小时前
Springboot整合Ollama实现调用本地多模型
java·spring boot·后端
霸道流氓气质2 小时前
Java 工程师 AI 智能体(Agent)完整学习路线
java·人工智能·学习
海石2 小时前
单调栈复健,顺便,牺牲一下吧,空间复杂度!一切献给AC
算法·leetcode
海石2 小时前
JS击败94%,Hard题想不到动态规划,那就用数组和栈试试
算法·leetcode
aaPIXa6222 小时前
C++模板元编程:编译期计算Fibonacci数列
java·开发语言·c++
SunnyDays10112 小时前
Java 编辑 PDF:从增删改查到加密保护
java·修改 pdf·编辑 pdf