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
相关推荐
bjzhang75几秒前
IDEA 2025.3重磅发布,Ultimate 终极版和 Community社区版二合一,免费版可商用
java·idea
程序猿零零漆3 分钟前
Spring之旅 - 记录学习 Spring 框架的过程和经验(三)Bean的依赖注入配置、Spring的其它配置标签
java·学习·spring
Marshmallowc3 分钟前
CSS 布局原理:为何“负边距”是栅格系统的基石?
前端·css·面试
算法与编程之美3 分钟前
解决tensor的shape不为1,如何转移到CPU的问题
人工智能·python·深度学习·算法·机器学习
natide4 分钟前
词汇/表达差异-8-Token Overlap(词元重叠度)
大数据·人工智能·深度学习·算法·自然语言处理·nlp·知识图谱
TT哇5 分钟前
@AllArgsConstructor
java·开发语言
lkbhua莱克瓦246 分钟前
TCP通信练习1——多发多收
java·开发语言·网络·网络协议·tcp/ip·tcp练习
这就是佬们吗7 分钟前
一文讲清---ELK搭建
java·笔记·elk·docker·容器
Filotimo_8 分钟前
在java后端开发中,docker虚拟化容器用处
java·开发语言·docker
hetao17338378 分钟前
2025-12-22 hetao1733837的笔记
c++·笔记·算法