Dynamic programming (the longest increasing subsequence) --- the longest common subsequence

Longest common subsequence

  For two subsequences S1 and S2, to find the longest common subsequence thereof.

  Dp define a two-dimensional array to store the length of the longest common subsequence, wherein dp [i] [j] denotes the longest common subsequence length of the front of the i-th character S1 and S2 of the first j characters in consideration with S1i S2j values ​​are equal, divided into two cases:

  • When S1i == S2j when it can be coupled with the basis of this value before S1i j-1 i-1 character before the character S1 and S2 of the longest common subsequence, plus the length of the longest common subsequence 1, i.e., dp [i] [j] = dp [i-1] [j-1] + 1.
  • When S1i! = S2j, the case of the longest common subsequence S1 of characters before i-1 and the first j characters of the longest common subsequence S2, or prior to i-th character S1 and S2 before the j-1 longest common subsequence character, who take their maximum, i.e. dp [i] [j] = max {dp [i-1] [j], dp [i] [j-1]}.

  For sequences of length S1 and S2 with the sequence length N of M, dp [N] [M] is the longest common subsequence length sequence S1 and sequence S2.

Compared with the longest increasing subsequence, longest common subsequence has the following differences:

  • For the two sequences, seeking their longest common subsequence.
  • The longest increasing sequence, dp [i] expressed in Si-terminated longest increasing sequence length, the sub-sequence must contain Si; in the longest common subsequence, dp [i] [j] S1 represents the front i-th character of the longest common subsequence S2, the first j characters in length, not necessarily contain S1i and S2j.
  • When seeking the final solution, the longest common subsequence dp [N] [M] is the final solution, and the longest increasing sequence dp [N] is not the final solution, because the SN to ending the longest sequence is not incremented must be the entire sequence of the longest increasing subsequence, we need to iterate over the array dp find the greatest.

Code:

public int lengthOfLCS(int []nums1,int []nums2){
    int n1=nums1.length;
    int n2=nums2.length;
    int [][]dp=new int[n1+1][n2+1];
    for(int i=1;i<=n1;i++){
        for(int j=1;j<n2;j++){
            if(nums1[i]==nums2[j]){
                dp[i][j]=dp[i-1][j-1]+1;
            }else{
                dp[i][j]=Math.max(dp[i-1][j],dp[i][j-1]);
            }
        }
    }
    return dp[n1][n2];
}

Guess you like

Origin www.cnblogs.com/yjxyy/p/11119207.html
Recommended