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开始走
相关推荐
文丑颜不良啊14 小时前
LeetCode3281~3300题目解析
java·leetcode
文丑颜不良啊18 小时前
LeetCode3261~3280题目解析
java·leetcode
Rain的Java大神之路20 小时前
LeetCode 40 组合总和 II:面试官想听的不是回溯,而是那行去重代码
java·leetcode·面试
ashiho1 天前
【LeetCode hot 100】3. 无重复字符的最长子串 (三种解法)
java·数据结构·后端·算法·leetcode·滑动窗口
Pniubi2 天前
01背包类问题-力扣416.分割等和子集
算法·leetcode·职场和发展
文丑颜不良啊2 天前
LeetCode3041~3060题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode3101~3120题目解析
java·leetcode
玄昌盛不会编程3 天前
LeetCode——2243. 计算字符串的数字和
java·算法·leetcode
文丑颜不良啊3 天前
LeetCode3061~3080题目解析
java·leetcode
文丑颜不良啊3 天前
LeetCode3081~3100题目解析
java·leetcode