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)

相关推荐
胖咕噜的稞达鸭1 小时前
算法入门:专题攻克一---双指针(3)有效三角形的个数 查找总价格为目标值的两个商品(剑指offer题目)
算法
毕设源码-朱学姐4 小时前
【开题答辩全过程】以 爱心捐赠网站为例,包含答辩的问题和答案
java·eclipse
尘觉6 小时前
中秋节与 Spring Boot 的思考:一场开箱即用的团圆盛宴
java·spring boot·后端
逻辑留白陈6 小时前
Adaboost进阶:与主流集成算法对比+工业级案例+未来方向
算法
Learn Beyond Limits6 小时前
Mean Normalization|均值归一化
人工智能·神经网络·算法·机器学习·均值算法·ai·吴恩达
天选之女wow6 小时前
【代码随想录算法训练营——Day28】贪心算法——134.加油站、135.分发糖果、860.柠檬水找零、406.根据身高重建队列
算法·leetcode·贪心算法
Gohldg6 小时前
C++算法·贪心例题讲解
c++·数学·算法·贪心算法
Le1Yu6 小时前
2025-10-7学习笔记
java·笔记·学习
popoxf6 小时前
spring容器启动流程(反射视角)
java·后端·spring
远远远远子6 小时前
类与对象 --1
开发语言·c++·算法