[Algorithm Cheat Sheat] —Longest Commom Subsequence

Leon .
1 min readApr 4, 2021

--

  1. What is LCS
  2. LCS solving by Recursion
  3. LCS solving bymemorization
  4. LCS solving by Dynamic Programming
  5. LIS
  6. edit-distance

What is LCS

LCS : Longeset Common Subsequence

A subsequence of a string is a new string generated from the original string with some characters(can be none) deleted without changing the relative order of the remaining characters. (eg, “ace” is a subsequence of “abcde” while “aec” is not). A common subsequence of two strings is a subsequence that is common to both strings.

subsequence 就是將字串以 sequence之形式做出拿或不拿的所有子集合。
(因為是sequence所以是有序的子集合)

Example :

Input: text1 = "abcde", text2 = "ace" 
Output: 3
Explanation: The longest common subsequence is "ace" and its length is 3.

Recursion Solving LCS

Dynamic Programming Solving LCS

Longest Increasing Subsequence (LIS)

直接看例子 :

Example:

Input: [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.

LIS問題以DP思維可以解決 :

時間複雜度 : O(N^2)

然而,LIS 用 Greedy 思維可以到 O(NlgN)的複雜度 :

https://leetcode.com/problems/longest-increasing-subsequence/discuss/74855/Short-C%2B%2B-STL-based-solution%3A-O(n-log-n)-time-O(1)-space-with-explanation

--

--

Leon .
Leon .

Written by Leon .

Record my life experience and knowledge , keep enthiusastic attitude to explore the world , that’s what I live for.

No responses yet