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
相关推荐
艾菜籽13 分钟前
Spring MVC练习:留言板
java·spring·mvc
左灯右行的爱情30 分钟前
4-Spring SPI机制解读
java·后端·spring
Code小翊31 分钟前
C语言bsearch的使用
java·c语言·前端
yong999031 分钟前
C#驱动斑马打印机实现包装自动打印
java·数据库·c#
好记忆不如烂笔头abc32 分钟前
linux系统记录登录用户的所有操作
java·linux·服务器
沐怡旸1 小时前
【穿越Effective C++】条款02:尽量以const, enum, inline替换#define
c++·面试
CptW1 小时前
第1篇(Ref):搞定 Vue3 Reactivity 响应式源码
前端·面试
sp421 小时前
一套清晰、简洁的 Java AES/DES/RSA 加密解密 API
java·后端
坚持编程的菜鸟1 小时前
LeetCode每日一题——三角形的最大周长
算法·leetcode·职场和发展
野犬寒鸦1 小时前
从零起步学习MySQL || 第五章:select语句的执行过程是怎么样的?(结合源码深度解析)
java·服务器·数据库·后端·mysql·adb