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
相关推荐
JieE2129 小时前
LeetCode 56. 合并区间|超清晰 JS 图解思路,面试高频区间题
javascript·算法·面试
Jack2017 小时前
HarmonyOS开发中错误处理策略:网络异常统一处理
算法
JustHappy18 小时前
我汇总了身边朋友的经历才发现,其实第一份实习是最难找的......
前端·后端·面试
uhakadotcom19 小时前
在python 的 工程化架构中 ,什么是 薄包装器层?
后端·面试·github
小小杨树19 小时前
读懂色彩:拍照调色不再难
算法·计算机视觉·配色
唐青枫1 天前
Java JDBC 实战指南:从 Connection 到事务和连接池
java
假如让我当三天老蒯1 天前
模块化:ES Module 与 CommonJS 的区别
前端·面试
沉默王二1 天前
面试官:RAG 不用向量数据库,用 MySQL 硬扛?我:100 万向量不是很轻松?
mysql·面试·ai编程
一个做软件开发的牛马1 天前
MyBatis-Plus 从零实战:完整搭建可运行 Demo,BaseMapper 零 SQL、Wrapper 条件构造、分页插件与代码生成器详解
java·后端