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
相关推荐
华仔啊2 小时前
为啥不用 MP 的 saveOrUpdateBatch?MySQL 一条 SQL 批量增改才是最优解
java·后端
千寻girling4 小时前
一份不可多得的 《 Django 》 零基础入门教程
后端·python·面试
SuperEugene4 小时前
Vue生态精选篇:Element Plus 的“企业后台常用组件”用法扫盲
前端·vue.js·面试
千寻girling4 小时前
Python 是用来做 AI 人工智能 的 , 不适合开发 Web 网站 | 《Web框架》
人工智能·后端·算法
Neptune14 小时前
JavaScript回归基本功之---类型判断--typeof篇
前端·javascript·面试
xiaoye20184 小时前
Lettuce连接模型、命令执行、Pipeline 浅析
java
颜酱7 小时前
一步步实现字符串计算器:从「转整数」到「带括号与优化」
javascript·后端·算法
离开地球表面_997 小时前
金三银四程序员跳槽指南:从简历到面试再到 Offer 的全流程准备
前端·后端·面试
UrbanJazzerati7 小时前
Scrapling入门指南:零基础也能学会的网页抓取神器
后端·面试
比尔盖茨的大脑7 小时前
事件循环底层原理:从 V8 引擎到浏览器实现
前端·javascript·面试