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
相关推荐
ting94520006 小时前
Humalike X Hermes 深度技术剖析:单指令注入群聊社交智能的底层架构、算法与跨 IM 平台实现
人工智能·算法·架构
吴声子夜歌6 小时前
Java面试——算法
java·算法·面试
evans在进步6 小时前
LeetCode 64:最小路径和——Java 原地动态规划详解
java·leetcode·动态规划
h_a_o777oah6 小时前
【图论】Tarjan 缩点:解决有向图中环的问题
c++·算法·图论·acm·强连通分量·缩点·tarjan
Tisfy6 小时前
LeetCode 1386.安排电影院座位:哈希表+位运算
算法·leetcode·散列表·题解·哈希表
Nil2087 小时前
leetcode 199二叉树的右视图
算法·leetcode·深度优先
凤山老林8 小时前
Spring Boot 3.x AOT 编译实战:从原理、踩坑到生产落地
java·spring boot·后端
博傅8 小时前
Spring 核心原理
java·后端·spring
yurenpai(27届找实习中)8 小时前
从零读懂 AI 智能客服(一):模块职责与 SSE 聊天链路(后端架构)
java·人工智能·架构·langchain4j
M78佐菲8 小时前
c语言学习笔记:排序与查找方法整理
linux·c语言·笔记·学习·算法