Leetcode 解题模版 - Search, Dynamic Programming

当一个大问题是由多个子问题构成时,我们可以通过不断分解问题来最终构建我们想求的大问题,这个过程称为搜索(Search)

搜索空间(Search Space)可以用tree的形式表现出来,便于理解

时间复杂度取决于这棵树的深度和每个节点的children个数

Search最重要的是定义好状态,保证每个子问题都能用一个状态来描述

DP(Dynamic Progamming)

如果我们重复Search Space有重复问题的话,可以记录下这些子问题的答案来保证不会重复计算多次。所有DP也被称为Search + Memorization

如此一来,时间复杂度就取决于子问题的个数

而搜索空间(Search Space)就可以用Tree的形式展现出来,便于理解。

所有DP都可以写成Bottom Up DFS 的形式。

只要定义好状态,可以从一个中间状态出发去思考递归规则

Bottom Up DFS 模版

  1. Define STATE of the problem

  2. Initialize memo to record calculated subproblems

  3. Return dfs(top_level_answer_state)

dfs(state):

  1. Base case check
  2. If current problem is calculated, return its answer
  3. For each subproblem x

a. Ask subproblem for their answers -> call dfs(sub_problem_state)

b. Build up current state problem answer based on subproblem answers

  1. Store current problem answer

Note: Step 2 & 4 are the difference for DP problems from search questions

例题

思路

对于单个Array或者String来说,一般只有2种定义状态:

  1. i = index or problem_length -> dp[i] 代表[0,i)的答案
  2. i,j = indexes -> dp[i][j] 代表array[i] ~ array[j] 这段subarray的答案

我们先从定义1 开始考虑,尝试是否可行

比如我们现在处于状态 i -> if we can break the word.substring(0,i)

记住DP一定是利用子问题的答案构建当前大问题答案

比如我们知道了子问题的答案是true -> we can break the word .substring(0,j)

那么剩下来的部分就是x =word.substring(j,n), 如果x是dictionary里的一个单词,那么整个问题 i 的答案就是true

把所有可能的 j = [0, i) 都试一遍,只要其中一个满足,整个问题的答案就是true

subproblem j + x

High Level:

  1. state = (length) -> state[i]: if we can break word.substring(0, length)

  2. initialize memo

  3. return dfs(n)

Implementation Steps

  1. Base case: i == 0 -> "" is breakable, return true
  2. if memo[i] != null -> problem has been calculated -> return memo[i]
  3. for each subproblem j from [0,i)

a. Ask subproblem for their answers -> call y = dfs(j)

b. if y == true and word.substring(j,n) in dictionary -> current prblem is true

  1. memo[i] = answer from step 3

  2. return memo[i]

时间复杂度: O(n**2)

相关推荐
GG不是gg几秒前
排序算法之线性时间排序:计数排序,基数排序,桶排序详解
数据结构·算法·排序算法
薯条不要番茄酱4 分钟前
【SpringBoot】从零开始全面解析SpringMVC (二)
java·spring boot·后端
亚里随笔9 分钟前
AlphaEvolve:LLM驱动的算法进化革命与科学发现新范式
人工智能·算法·llm·大语言模型
zhougl99610 分钟前
OkHttp用法-Java调用http服务
java·http·okhttp
越城13 分钟前
深入理解二叉树:遍历、存储与算法实现
c语言·数据结构·算法
oioihoii22 分钟前
C++23 中的 ranges::fold_left:范围折叠算法
算法·c++23
跟我一起学测试呀24 分钟前
软件测试—接口测试面试题及jmeter面试题
软件测试·jmeter·面试
zyhomepage1 小时前
科技的成就(六十八)
开发语言·人工智能·科技·算法·内容运营
{⌐■_■}1 小时前
【计算机网络】HTTP/1.0,HTTP/1.1,HTTP/2,HTTP/3汇总讲解,清晰表格整理面试重点对比
计算机网络·http·面试
瑞雪兆丰年兮1 小时前
数学实验(Matlab编程基础)
开发语言·算法·matlab·数学实验