---
# System prepended metadata

title: 1143-Longest Common Subsequence
tags: [Medium]

---

# 1143-Longest Common Subsequence
###### tags: `Medium`
## Question
https://leetcode.com/problems/longest-common-subsequence/
## Key
1. DP
2. same sub-sequence:字元順序一樣 但位置不一定要一樣
    same sub-string:字元位置一樣


## Reference

## DP Solution
```cpp=
// dp[i][j] text1前i个和text2前j个字元最長共同子序列，元素代表長度，只要出現字元相同且順序一樣，就會一直累加
// dp[m+1][n+1]
//   ' a d c e
// ' 0 0 0 0 0
// a 0 1 1 1 1
// c 0 1 1 2 1
//
class Solution {
public:
    int longestCommonSubsequence(string text1, string text2) {
        int x=text1.size(),y=text2.size();
        int grid[x+1][y+1];
        //initialize the dp matrix
        for(int i=0;i<x+1;i++)
        {
            grid[i][0]=0;
        }
        for(int i=0;i<y+1;i++)
        {
            grid[0][i]=0;
        }
        
        for(int i=1;i<x+1;i++)
        {
            for(int j=1;j<y+1;j++)
            {
                if(text1[i-1]==text2[j-1])
                {
                    grid[i][j]=grid[i-1][j-1]+1;
                }
                else
                {
                    grid[i][j]=max(grid[i-1][j],grid[i][j-1]);
                }
            }
        }
        return grid[x][y];
    }
};
```
