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开始走
相关推荐
hold?fish:palm29 分钟前
7 接雨水
开发语言·c++·leetcode
tkevinjd2 小时前
力扣148-排序链表
算法·leetcode·链表
wabs66619 小时前
关于图论【力扣797.所有可能的路径的思考】
算法·leetcode·图论
Navigator_Z1 天前
LeetCode //C - 1156. Swap For Longest Repeated Character Substring
c语言·算法·leetcode
兰令水1 天前
hot100【acm版】【2026.7.19打卡-java版本】
java·数据结构·算法·leetcode·面试
tkevinjd1 天前
力扣72-编辑距离
算法·leetcode·职场和发展
什巳2 天前
JAVA练习309- 二叉树的层序遍历
java·数据结构·算法·leetcode
什巳2 天前
JAVA练习306- 翻转二叉树
java·数据结构·算法·leetcode
smj2302_796826522 天前
解决leetcode第3989题网格中保持一致的最大列数
python·算法·leetcode
CoderYanger2 天前
A.每日一题:3020. 子集中元素的最大数量
java·程序人生·算法·leetcode·面试·职场和发展·学习方法