Dynamic programming

  • Solving LCS (Longest Common Sub sequence) using dynamic programming
  • Solving Fibonacci sequence problem using dynamic programming
  • Solving matrix chain multiplication problem using dynamic programming

Solving LCS (Longest Common Sub sequence) using dynamic programming

#include<stdio.h>
#include<string.h>

int i,j,m,n,dp[20][20]; // Dynamic programming table
char seq1[20],seq2[20],direction[20][20]; // Sequences and direction table

void printLCS(int i,int j)
{
    if(i==0 || j==0)
        return;
    if(direction[i][j]=='c')
    {
        printLCS(i-1,j-1);
        printf("%c",seq1[i-1]);
    }
    else if(direction[i][j]=='u')
        printLCS(i-1,j);
    else
        printLCS(i,j-1);
}

void longestCommonSubsequence()
{
    m=strlen(seq1);
    n=strlen(seq2);
    for(i=0;i<=m;i++)
        dp[i][0]=0;
    for(i=0;i<=n;i++)
        dp[0][i]=0;

  
    for(i=1;i<=m;i++)
        for(j=1;j<=n;j++)
        {
            if(seq1[i-1]==seq2[j-1])
            {
                dp[i][j]=dp[i-1][j-1]+1;
                direction[i][j]='c';
            }
            else if(dp[i-1][j]>=dp[i][j-1])
            {
                dp[i][j]=dp[i-1][j];
                direction[i][j]='u';
            }
            else
            {
                dp[i][j]=dp[i][j-1];
                direction[i][j]='l';
            }
        }
}

//In the above, c signifies a diagonal movement, u represents an upward shift, and l indicates a downward shift.
int main()
{
    printf("Enter 1st sequence:");
    scanf("%s",seq1);
    printf("Enter 2nd sequence:");
    scanf("%s",seq2);
    printf("\nThe Longest Common Subsequence is ");
    longestCommonSubsequence();
    printLCS(m,n);
    return 0;
}

  • Solving Fibonacci sequence problem using dynamic programming
Scroll to Top