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
相关推荐
untE EADO3 分钟前
Tomcat的server.xml配置详解
xml·java·tomcat
ictI CABL12 分钟前
Tomcat 乱码问题彻底解决
java·tomcat
敖正炀15 分钟前
DelayQueue 详解
java
敖正炀41 分钟前
PriorityBlockingQueue 详解
java
shark22222221 小时前
Spring 的三种注入方式?
java·数据库·spring
workflower1 小时前
机器人应用-楼宇室内巡逻
大数据·人工智能·算法·microsoft·机器人·动态规划·享元模式
ZPC82101 小时前
fanuc 机器人通过PR寄存器实现轨迹控制
人工智能·算法·计算机视觉·机器人
陈煜的博客1 小时前
idea 项目只编译不打包,跳过测试,快速开发
java·ide·intellij-idea
py有趣1 小时前
力扣热门100题之编辑距离
数据结构·算法·leetcode
JAVA学习通1 小时前
LangChain4j 与 Spring AI 的技术选型深度对比:2026 年 Java AI 工程化实践指南
java·人工智能·spring