leetcode hot100 1143. 最长公共子序列 mediuim 递归优化


递归优化 @cache

每个算一次:状态数 = m × n , 时间复杂度 = O(m × n)

空间复杂度 O(m × n)

python 复制代码
class Solution:
    def longestCommonSubsequence(self, text1: str, text2: str) -> int:

        # 可以跳着选(不连续),但顺序不能变
        @cache
        def dfs(i, j):
            # 任意一个走到头
            if i == len(text1) or j == len(text2):
                return 0
            
            # 相等 → 一起走
            if text1[i] == text2[j]:
                return 1 + dfs(i + 1, j + 1)
            
            # 不等 → 各走一步,取最大
            return max(
                dfs(i + 1, j),   # 跳过 text1[i]
                dfs(i, j + 1)    # 跳过 text2[j]
            )
        
        return dfs(0, 0)  # 两个指针 i, j:两个数组都从0开始走
相关推荐
j7~13 小时前
【穷举、深搜与回溯算法】一棵决策树讲透全排列与子集
数据结构·c++·算法·leetcode·回溯·递归
Shaoshing14 小时前
LeetCode100 42.接雨水
java·算法·leetcode
文丑颜不良啊15 小时前
LeetCode1261~1280题目解析
java·leetcode
Shaoshing16 小时前
LeetCode100 11. 盛最多水的容器
算法·leetcode
海绵宝宝转agent17 小时前
Leetcode二叉树算法个人理解
笔记·学习·算法·leetcode·深度优先
Rain的Java大神之路17 小时前
面试被LeetCode 27(移除元素)问懵?别再用两层 for 循环了:一道“简单题”吃透双指针原地删除,附面试加分话术 + 11 个避坑清单
后端·leetcode·面试
重生之小比特19 小时前
【算法拾光】前缀和|连续的子数组和 + 和相同的二元子数组
算法·leetcode·哈希算法
Pniubi19 小时前
力扣 102二叉树的层序遍历(广度优先搜索)
leetcode·宽度优先
一去不复返的通信er19 小时前
力扣15:盛最多水的容器
算法·leetcode
Navigator_Z19 小时前
LeetCode //C - 1309. Decrypt String from Alphabet to Integer Mapping
c语言·算法·leetcode