Learn Dynamic Programming Basic to Advanced

Learn Dynamic Programming Basic to Advanced

October 10, 2026·30 min read·
#DP#DSA#recursion

Learn Dynamic Programming Basic to Advanced

Learn Dynamic Programming Basic to Advanced

Those who can not remember the past are condemned to repeat it.

Note : Recursion is prerequisite to learn DP

We are going to learn DP through problem solving and learning some pattern which help us to learn DP .

  • Basics

  • Knapsack problems

    • Bounded knapsack (0/1)
    • Unbounded knapsack
  • Dp on stocks

  • Longtest common subsequence (LIS)

  • Longtest increasing subsequence (LIS)

  • Matix chain multiplication

  • Path recovery mechanism

  • Converting recursive solution into Tabulation

Lets start learning through one of classical problem which give us idea why we need dp , how we can calculate Time and Space complexity of DP solution.

Basic DP Problems

  • Basics

Fibonacci number

Problem statement

Find the nth fibonacci number given that

fib(0) = 0 fib(1) = 1 0 <= n <= 10^5

Recursive solution

int fib(int n) {
    //base cases
    if (n==0) return 0;
    if (n==1) return 1;
		
	return fib(n-1)+fib(n-2);
}

enter image description here

Now looking to this recursion tree we can see that some functions calls are unneccessery means we can ignore those repeatative calls by memoizing those result and use it again in constant time enter image description here

Recursion TC = number of function calls * time take by one functional call

Recursion SC = max size of stack at any time = height of tree

Time and Space complexity for recusive solution

TC = O(2^n)

SC = O(n)

Lets apply memoization to recursive solution

const int N = 1e5; // depends on input size

int dp[N] ;  

int fib(int n):
    if (n==0):
        return 0;

    if (n==1):
        return 1;

    if (dp[n]!=-1 ):
        return dp[n];

    return dp[n] =  f(n-1)+f(n-2);


int main(){
	int n;
	cin >> n;
	memset(dp,-1,sizeof dp) // intializing dp with -1
	cout << fib(n)
}

Now the Time and Space complexity are -

TC = O(n)

SC = O(n)

Now you guys can try to solve this similar problem which based on same basic dp patterns.

S .NoLinks
1https://leetcode.com/problems/fibonacci-number/description/
2https://leetcode.com/problems/climbing-stairs/
3https://leetcode.com/problems/min-cost-climbing-stairs/
4https://leetcode.com/problems/minimum-path-sum/description/
5https://www.geeksforgeeks.org/problems/geek-jump/1

House rober I

Threr are n houses , each house has a certain amount of money . As a professional robber u want to rob the money , the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

enter image description here

Example N= 5

houses[] = [100 , 50 , 70 , 70 , 20 ]

So we need to try each possible combination of house and maximize the profit

we have to try every possible ways

let suppose n =10

if we start = House 1

     1-> 3 -> 5 -> 7-> 9
     1 -> 4 -> 6 -> 8 -> 10
     1 -> 5-> 7 -> 9
     1 -> 6-> 8 -> 10
     1 -> 7 -> 9
     1 -> 10
    ..

we start = House 2

     2 -> 4 -> 6 -> 8 ->10
     2 -> 5 -> 7 -> 9
    .
    .

So here we can think of choosing a house or not choose a house to rob means consider or not consider this house for a index i

Recursive solutions

int f(int idx , int n , int arr[]) :

    if(idx>=N) :
        return 0; // reached the end of houses
    
    // rob this house
    ans1 = arr[idx]+f(idx+2,n,arr)

    // skip this house
    ans2 = f(idx+1,n,arr)

    return max(ans1,ans2)

main() :

    int N;
    int arr[N]
    print f(0,N,arr)

TC :O(2^N)

SC : O(N)

Lets apply memoization to recursive solution

int *dp;

int f(int idx , int n , int arr[]) :

    if(idx>=N) :
        return 0;
    
    if(dp[idx]!=-1):
        return dp[idx]

    // rob this house
    ans1 = arr[idx]+f(idx+2,n,arr)

    // skip this house
    ans2 = f(idx+1,n,arr)

    return dp[idx] =  max(ans1,ans2)

main() :

    int N;
    int arr[N]
    dp = new int[N+1]
    memset(dp,-1,sizeof(dp))
    print f(0,N,arr)
    

TC = O(n)

SC = o(n)


Knapsack DP problems

Bounded knapsack

  • 0/1 Knapsack

Problem Statement

Given two arrays, cost and wts[], where each element represents the value and weight of an item respectively, and an integer W representing the maximum capacity of the knapsack (the total weight it can hold).

Put the items into the knapsack such that the total value obtained is maximum without exceeding the capacity W.

Note: You can either include an item completely or exclude it entirely — fractional selection of items is not allowed. Each item is available only once. enter image description here

Recursive solution

f(int idx ,  int currentCapacity):
    
    if(idx>=n):
        return 0

    // take it - if possible
    if(currentCapacity+weight[idx]<=capacity)
        ans1 = profit[idx]+f(idx+1,currentCapacity+weight[idx])

    // not take it
    ans2 = f(idx+1,currentCapacity)

    return max(ans1,ans2)

main() :

    int n , capacity (max capacity/ W)
    int weight[n]
    int profit[n]
    print f(0,0)

TC = o(2^n)

SC = O(n)

Lets apply memoization to recursive solution

const int N = 1e3;

const int W  =1e3;

int dp[N][W+1];


f(int idx ,  int currentCapacity):

    if(idx>=n):
        return 0

    if(dp[idx][currentCapacity] != -1] ) :
        return dp[idx][currentCapacity]

    // take it
    int ans1 = 0
    if(currentCapacity+weight[idx]<=capacity)
        ans1 = profit[idx]+f(idx+1,currentCapacity+weight[idx])

    // not take it

    ans2 = f(idx+1,currentCapacity)

    return dp[idx][currentCapacity]  = max(ans1,ans2)

main() :

    int n , capacity 
    int weight[n]
    int profit[n]
    memset(dp,-1,sizeof dp)
    print f(0,0)

TC = O(n*C)

SC = O(n*C)

Unbounded knapsack

  • 0/1 Knapsack

Problem statement

Given a knapsack with a fixed capacity and a set of n items, where each item has an associated value cost[i] and weight weight[i], determine the maximum profit that can be obtained by filling the knapsack. Each item can be selected an unlimited number of times. enter image description here

Recursive solution

f(int idx ,  int currentCapacity):

    if(idx>=n):
        return 0

    // take it - if possible means in knapsack we have enough space
    if(currentCapacity+weight[idx]<=capacity)
        ans1 = profit[idx]+f(idx,currentCapacity+weight[idx]) // idx not idx+1 becuase we can take it again

    // not take it
    ans2 = f(idx+1,currentW)

    return max(ans1,ans2)

main() :

    int n , capacity 
    int weight[n]
    int profit[n]
    print f(0,0)
    

TC = O(exponention)

SC = O(exponention)

Lets apply memoization to recursive solution

f(int idx ,  int currentCapacity):

    if(idx>=n):
        return 0

    if(dp[idx][currentCapacity] != -1] ) :
        return dp[idx][currentCapacity]

    // take it - if possible means we have enough sapce in bag
    int ans1 = 0
    if(currentCapacity+weight[idx]<=capacity)
        ans1 = profit[idx]+f(idx,currentCapacity+weight[idx])

    // not take it
    ans2 = f(idx+1,currentCapacity)

    return dp[idx][currentCapacity]  = max(ans1,ans2)

main() :

    int n , capacity 
    int weight[n]
    int profit[n]
    dp[n][capacity +1] // fill it -1
    print f(0,0)
    

TC = O(n*C)

SC = O(n*C)

Now you guys can try to solve this similar problem which based on same Knapsack dp patterns.

S .NoLinks
1https://leetcode.com/problems/house-robber/
2https://leetcode.com/problems/house-robber-ii/
3https://www.geeksforgeeks.org/problems/0-1-knapsack-problem0945/1
4https://www.geeksforgeeks.org/problems/subset-sum-problem-1611555638/1
5https://leetcode.com/problems/partition-equal-subset-sum/
6https://www.geeksforgeeks.org/problems/perfect-sum-problem5633/1
7https://www.geeksforgeeks.org/problems/partitions-with-given-difference/1
8https://leetcode.com/problems/target-sum/description/
9https://www.geeksforgeeks.org/dsa/unbounded-knapsack-repetition-items-allowed/
10https://cses.fi/problemset/task/1636
11https://cses.fi/problemset/task/1635
12https://leetcode.com/problems/coin-change/description/
13https://leetcode.com/problems/coin-change/
14https://www.geeksforgeeks.org/problems/rod-cutting0840/1

Stacks DP problems

enter image description here

BUY AND SELL STOCK

One Transaction Allowed

Problem Statement

Given a prices[n] array of a stock for n days . means prices[i] is price of stock on particular ith days. We are given number of transaction (for this case - one transaction allowed means - BUY+SELL ) and then we need to maximize the profit buy choosing best combination of days to perform those number of transactions or less to gain max profit.

Example int n = 6

prices[] = [10 2 9 1 3 5]

by trying ith with j = i+1 to n days we can check what max profit we can get for each ith days

best profit = [-1 7 -4 4 2 0]

Brute force solution comes firstly in our mind is by checking is possible ways to do transaction

ans =0 


for(int i = 0 ; i < n ; i++ ) :

    // buying on ith day
    int mx = 0
    
    for(int j = i +1 ; j <n ; j++ :
        mx = max(mx,prices[j])

    ans  =  max(ans,prices[i]-mx)

print(ans)

TC = O(n^2)

SC = O(1)

Even we can further optimized this solution to o(n) but lets try to find out a recursive in general solution which work even for k or unlimited number of transaction.

So this is not accepted solution which we want .

Lets think recursive way , means on a particular ith day we have 2 options to explore

  1. Don't perform any transaction (means no buy or sell)
  2. Try to explore possible transaction (means either or sell)

So we can explore all possible ways using this methods . lets see how recursive code looks like and how it works

Recursive solution

const int BUY = 0
const int SELL = 1

int solve(int index,int trasactionType) :

    if(index==n)
        return 0

    // skip this day -  means no transaction
    ans1 = solve(index+1,trasactionType)

    
    // perform the possible transactions
    if trasactionType == BUY :
        ans2 = -prices[index]+solve(index+1,SELL) // we need to pay price to buy it
    else :
        ans2 = +prices[index]// break as 1 txs + getting benefits of prices[i] amount
        // its is overall as mxProfit  = max_selling_price - min_buying_price

    return max(ans1,ans2)

main():

    //input
    ans = solve(0,BUY)

TC= o(n^2)

SC = O(n)

as we can see for every ith day we have 2 options to choose and visualize using recursive tree enter image description here

Lets apply memoization to recursive solution

const int BUY = 0
const int SELL = 1
const int N = 1e5;
int dp[N][2];

int solve(int index,int trasactionType) :

    if(index==n)
        return 0

    if(dp[index][trasactionType] != -1 ) :
        return dp[index][trasactionType]

    // skip this day
    ans1 = solve(index+1,trasactionType)

    
    // perform the possible transactions
    if trasactionType===BUY:
        ans2 = -prices[index]+solve(index+1,SELL)
    else :
        ans2 = prices[index]// break as 1 txs

    return dp[index][trasactionType] =  max(ans1,ans2)


main():
    //input
    // memset(dp,-1,sizeof dp)
    print solve(0,BUY);
    

TC= O(2*n)

SC = O(2*n)

At most K Transaction Allowed

enter image description here

Recursive solution

const int BUY = 0
const int SELL = 1

int solve(int index,int event) :
    
    if(event == 2*k(4) or index==n) // either reached end or number of transaction fullfilled 
        return 0

    // skip this day
    ans1 = solve(index+1,event)

    // perfoming the possible events/ transaction
    int transactionType = event % 2 == 0 ? BUY : SELL
	int ans2 = 0
    if transactionType == BUY :
        ans2 = -prices[index]+solve(index+1,event+1)
    else :
        ans2 = prices[i]+solve(index+1,event+1)
    
    return max(ans1,ans2)

main():
    //input
    ans = solve(0,0) // (index,event)
    

TC= O(2*n)

SC = O(2*n)

Lets apply memoization to recursive solution

const int BUY = 0
const int SELL = 1
const int N = 1e5;
const int K = 2
int dp[N][2*K];

int solve(int index,int event) :

    if(event == 2*K(4) or index==n)
        return 0

    if(dp[index][event] != -1 ) :
        return dp[index][event]

    // skip this day
    ans1 = solve(index+1,event)

    // perfoming the possible events/ transaction
    int transactionType = event%2 ==0 ? BUY :SELL
	int ans2 = 0 ;
    if transactionType == BUY :
        ans2 = -prices[index]+solve(index+1,event+1)
    else :
        ans2 = prices[i]+solve(index+1,event+1)
    
    return dp[index][event]= max(ans1,ans2)

main():

//input
memset(dp,-1,sizeof dp)
ans = solve(0,0)

TC = O(K*N)

SC = O(K*N)

here k = 2

Now you guys can try to solve this similar problem which based on same Stocks dp patterns.

S .NoLinks
1https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
2https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/
3https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
4https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/
5https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/
6https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/

LCS(Longest Common Subsequence ) DP Problems

Subsequence

subsequence can be continoues or dis continues but element should follow the order as they appear in array or string. enter image description here

Check a subsequence

Problem Statement Given 2 string s and t , check t is subsequence of s or not ?

Solution

  1. We can generate all subsequence and compare with t (TC = exponentional)
  2. Check t is part of s or not using 2 pointer - O(linear)

Example

s = "ccdegf"
t  = "def"
n = len(s) = 6 ,  m = len(t) = 3
i = 0 (i goes to n-1)
j = 0 (j goes to n-2)

case 1: check both current char of s and t and if matches then consider and move i+1, j+1 and check further

case 2: if not equal then move i+1 becuase we want to match string t char with s , so try j with i+1

At last check if j reached end means , string t cover fully so t is subsequence of s.

Solution

bool isSubsequence(string s,string t){
    int i  = 0 ,  n = s.size();
    int j  = 0 ,  m = t.size();

    while(i<n and j < m){
        if(s[i]==t[j]){
            i++;
            j++;
        }
        else{
            i++;
        }
    }
    return j==m;
}

TC = O ( max ( n , m ) ) => O( n )

So now the same concept can be applied to find longtest common subsequence.

Longtest common subsequence - LCS

Problem Statement

Given 2 strring s1 and s2 find LIS .

Example

s1 = abcdecfrqpfg
s2 = cdfzxpya
find the lcs of  s1 and s2

enter image description here

Recursive solution

solve(int i , int j ) :

    if(i==n or j==m):
        return 0

    int ans = 0 ;

    if s1[i] == s2[j] :
				// means this char is common b/w s1,s2 count it so +1
        ans = 1 + solve(i+1,j+1)

    else :
		// ignore ith character of s1 so we can check s1[i+1...n-1] window with s2[j...m-1] window 
        ans1 = solve(i+1,j)
				
		// ignore jth character of s2 so we can check s2[j+1...m-1] window with s2[i...n-1] window
        ans2 = solve(i,j+1)
				
        //wanted to find longest so max of both cases
        ans = max(ans1,ans2)

return ans

TC = O(2 ^ K)

Sc = O(K)

Here K = max(n,m)

To visualize this code u can check try drawing a recursive tree for small example but I wants you guys to trust your recursive solution , becuase every time its not that easy to draw and understood by tree. enter image description here

Lets apply memoization to recursive solution

int dp[n][m] // -1


solve(int i , int j ) :

    if(i==n or j==m):
        return 0

    if(dp[i][j]!=-1) return dp[i][j]

    int ans = 0 ;

    if s1[i] == s2[j] :

        ans = 1 + solve(i+1,j+1)

    else :

        ans1 = solve(i+1,j)

        ans2 = solve(i,j+1)

        ans = max(ans1,ans2)

    return dp[i][j] =  ans

main() :
    input
    memset(dp,-1,sizeof dp)
    print solve(0,0)
   

TC = O(n*m)

Sc = O(n*m)

Now you guys can try to solve this similar problem which based on same LCS dp patterns.*

S.NoLinks
1https://leetcode.com/problems/longest-common-subsequence/description/
2https://www.geeksforgeeks.org/problems/lcs-of-three-strings0028/1
3https://leetcode.com/problems/edit-distance/
4https://leetcode.com/problems/delete-operation-for-two-strings/description/
5https://leetcode.com/problems/distinct-subsequences/description/
6https://leetcode.com/problems/longest-palindromic-subsequence/
7https://leetcode.com/problems/shortest-common-supersequence/description/
8https://leetcode.com/problems/minimum-insertion-steps-to-make-a-string-palindrome/

LIS(Longest Increasing Subsequence ) DP Problems

Before we start , it is same as finding LCS but the elements are in subsequence are should be in increasing order ( a < b ).

Also Difference b/w increasing and non-decreasing should clear to you. Increasing = a < b Non-decreasing = a <= b

LIS - Technique I

Problem Statement Given a array of interger arr[n] with n element we need to find longest increasing subsequence possible.

Example

A[9] = [1 7 5 2 9 3 5 11 18]

| A[i] | <= 10^9

enter image description here

clearly we can see we need to remember previous element so that we can compare with current and check prevElement < currentElement then we can pick this element .

Recursive solution

int f (int index,int prevIndex,int A[]) :

    // base case
    if (index == A.size())
        return 0;

    // not take
    int ans1 = solve(index+1,prevIndex,A)

    // take- if possible
    int ans2 = 0 ;
		
		// just if no element still pick so pick current
    if(prevIndex==N or A[prevIndex] < arr[index])
        ans2 = 1 + solve(index+1,index,A)

    return  max(ans1,ans2)


main:
    input
    cout << solve(0,N,A)

TC = O(2^n)

SC = O(n)

Lets apply memoization to recursive solution

int N = 1e3
int dp[N][N+1]

int f (int index,int prevIndex,int A[]) :

    // base case
    if (index == A.size())
        return 0;

    if(dp[index][prevIndex]!=-1)
        return dp[index][prevIndex];

    // not take
    int ans1 = solve(index+1,prevIndex,A)

    // take- if possible
    int ans2 = 0 ;
    if(prevIndex==N or A[prevIndex] < arr[index])
        ans2 = 1 + solve(index+1,index,A)

    return dp[index][prevIndex] = max(ans1,ans2)


main:
    input
    memset(dp,-1,sizeof dp)
    cout << solve(0,N,A)
    

TC = O(n*n)

SC = O(n)

Note : This solution only works for n <= 2000 means if constraints are high / tight .

So lets think of another technique which helps us solve this questions in O (n log n) time.

For that lets learn technique which uses tabulation . But don't worry about tabulation for now we will see converting our dp solution in tabulation , path recovery and space optimization techniques as well as . But for now lets not think like converting this dp solution into tabulation think of it like we are learning new technique to solve dp (lis) problem.

LIS - Technique II

Same problem statment given , just lets try to create a dp array which tell us about length of LIS. what exactly is that ?

Array given of length n.

let suppose

n = 9

A[n] = [1 7 5 2 9 3 5 11 18] .

we are going to form a dp array of same length dp[n].

dp[n] = [ _ , _ , _ , _ , _ , _ , _ , _ , _ _] where

dp[i] = length of LIS which ending at ith index (ith element included)

simple way to say that

dp[i] = length of LIS ending at i

There is a 2 example given below in diagram so which helps you guys to understand how to fill dp array

enter image description here

lets see in example I

dp[5] = 3 how ??

So we can see index=5 we have element 3 which can extend either index = 3 or index = 1. with index = 1 LIS = [1,2,3] with index = 3 = [2,3]

but its making sense to take where we extending with index=1 , we getting longest with index=1,2,3 which is of length 3.

So our answer is going to be max element from dp array

answer = maximum element from dp array

Solution

vector<int>dp(n)

for(int i = 0 ;  i < N ; i++ ) :

    dp[i] = 1 // single element always form LIS

    for(int j = i-1 ; j >= 0 ; j--):

        if A[j] < A[i]:
        
            dp[i] = max(dp[i],1 + dp[j]) // best one to extend


cout << *max_element(dp.begin(),dp.end());

    

TC = O(n*n)

SC = O(n)

Even we can write further optmized way by intilazing the dp with 1 .

vector<int>dp(n,1)

for(int i = 0 ;  i < N ; i++ ) :

    for(int j = i-1 ; j >= 0 ; j--):

        if A[j] < A[i]:
        
            dp[i] = max(dp[i],1 + dp[j]) // best one to extend


cout << *max_element(dp.begin(),dp.end());

Path priting I will provide solution which u guys can try to understand how this works (DAG - Directed acyclic graph)

int main() {


    int n;
    cin >> n
    vector<int>arr(n);

    for(int i = 0 ; i < n  ; i++)
        cin >> arr[i];


    // technique 2
    vector<int>dp(n,1);// single element always make sub seq
    vector<int>parent(n,-1);

    for(int i = 0 ; i< n ; i++){
        for(int j = i-1 ; j>= 0 ; j--){
            if(arr[j]<arr[i] and 1 + dp[j] > dp[i]){
                dp[i] = 1 + dp[j]; // we can extend with prev result
                parent[i]=j;// moving to parent
            }
        }
    }


    int idx = max_element(dp.begin(),dp.end()) -dp.begin();
    cout << dp[idx] << endl;

    vector<int>lis;

    while(idx!=-1){
        lis.push_back(arr[idx]);
        idx=parent[idx];
    }
    reverse(lis.begin(),lis.end());
    for(auto &x:lis)cout << x << " ";

enter image description here

Optmising LIS solution to n*n to n log n

Example

A = [ 10 9 2 5 3 7 101 18 ]

Dp = [ 1 1 1 2 2 3 4 4 ]

So now we can create candidate(n+1,0) where

candidate[i] => represent best element for length i of LIS

enter image description here

Best candidate for each length so now lets maintain only best candidate at each level enter image description here

Note: : From this method only we get is length of LIS , but the elements we are getting in candidate array are not be form subsequence . They are just best candidate possible for the level .

Solution

vector<int>candidate(n+1,INT_MAX)

candidate[0] = INT_MIN

for(int i = 0 ; i < n; i++) :

    auto it = lower_bound(candidate.begin(),candidate.end(),A[i])
    
    *it = A[i] // replace that place with


int ans = 0;
for(int i = 1 ; i<=n;i++):
    if(candidate[i]==INF)break;
    ans++;

cout << ans;

    

TC = O(n*log (n) )

SC = O(n)

So this method can also be used to find LIS but for that we need to form dp array which can be done with same code.

Now you guys can try to solve this similar problem which based on same LIS dp patterns.*

S.NoLinks
1https://leetcode.com/problems/longest-increasing-subsequence/
2https://www.geeksforgeeks.org/problems/minimum-number-of-deletions-to-make-a-sorted-sequence3248/1
3https://leetcode.com/problems/minimum-number-of-removals-to-make-mountain-array/solutions/1166577/total-length-length-of-longest-bitonic-sequence/
4https://leetcode.com/problems/increasing-triplet-subsequence/description/
5https://leetcode.com/problems/russian-doll-envelopes/

Path Recovery Mechanism

Lets learn path recovery through one of the example we already solved with recursion + memoization . So now lets find actual path for that.

LCS (longtest common subsequence)

Example

	s1 = "axyb"
	s2 = "abyxb"
	
	output = "axb"

DP Solution (REC + MEMO)

const int N = 1e3;
int dp[N][N];

int solve(int i , int j , string &s1, string &s2){

    // base case
    if(i>=s1.size() or j >= s2.size()){
        return 0;
    }

    if(dp[i][j]!=-1){
        return dp[i][j];
    }

    // character match
    int ans =  0;
    if(s1[i]==s2[j]){
        ans = 1 + solve(i+1,j+1,s1,s2);
    }else{
        // no match
        // lets move i forward and check
        int ans1 = solve(i+1,j,s1,s2);

        // lets move j forward and check
        int ans2 = solve(i,j+1,s1,s2);

        ans = max(ans1,ans2);
    }
    return  dp[i][j] =  ans;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    string s1,s2;
    cin >>s1 >> s2;

    memset(dp,-1,sizeof dp);
    
    cout << solve(0,0,s1,s2);

    return 0;
}

But this solution gives us length of LCS not that exact LCS we want as output. So for that we can use path recovery mechanism which follow same as solve function just not returning anything but saving our choice of taken at particular time.

So Steps to write path revovery function -

1. Initialize a global variable(string or array) to store the result

    string lcs = "";

2. Copy whole solve function and use it with another name as recover and make it void , replace return with no return and remove dp part from there

    void recover(int i , int j , string &s1, string &s2){

    // base case
    if(i>=s1.size() or j >= s2.size()){
        return ;
    }
    // character match
    int ans =  0;
    if(s1[i]==s2[j]){
        ans = 1 + solve(i+1,j+1,s1,s2);
    }else{
        // no match
        // lets move i forward and check
        int ans1 = solve(i+1,j,s1,s2);

        // lets move j forward and check
        int ans2 = solve(i,j+1,s1,s2);

        ans = max(ans1,ans2);
    }
}

3. Now the position we returning (base case + another cases) return nothing and at solve function calls , add logic to add choice and call recover function if needed. (For few base cases it depened on problem to add choive or not )

void recover(int i , int j , string &s1, string &s2){

    // base case
    if(i>=s1.size() or j >= s2.size()){
        return ;
    }
    // character match
    int ans =  0;
    if(s1[i]==s2[j]){
        
        ans = 1 + solve(i+1,j+1,s1,s2);
        
        result.push_back(s[i]; // as this char is part of LCS
        recover(i+1,j+1,s1,s2);
        
    }else{
        // no match
        // lets move i forward and check
        int ans1 = solve(i+1,j,s1,s2);

        // lets move j forward and check
        int ans2 = solve(i,j+1,s1,s2);

        ans = max(ans1,ans2);
				
	    if(ans==ans1){
			    recover(i+1,j,s1,s2);
	    }else{
		    recover(i,j+1,s1,s2);
	    }
    }
}

So This recover function works in in same time as solve and the calls of solve in recover are in constant time because at time of solve calls they are already stored in dp array.

Complete Path Recovery Code

#include <bits/stdc++.h>
using namespace std;

const int N = 1e3;
int dp[N][N];

string result = "";

int solve(int i,int j,string &s1,string &s2){

    // base case
    if(i==s1.size() or j==s2.size()){
        return 0;
    }

    if(dp[i][j]!=-1) return dp[i][j];

    int ans = 0 ;
    // both current char ares equal
    if(s1[i]==s2[j]){
        ans = 1 + solve(i+1,j+1,s1,s2);
    }else{
        // take it i wala - ignoring j wala
        int ans1 = solve(i,j+1,s1,s2);

        // take it j wala - ignoring i wala
        int ans2 = solve(i+1,j,s1,s2);

        ans = max(ans1,ans2);
    }

    return dp[i][j] = ans;
}

void recover(int i , int j , string &s1, string &s2){

    // base case
    if(i>=s1.size() or j >= s2.size()){
        return ;
    }
    // character match
    int ans =  0;
    if(s1[i]==s2[j]){
        
        ans = 1 + solve(i+1,j+1,s1,s2);
        
        result.push_back(s[i]; // as this char is part of LCS
        recover(i+1,j+1,s1,s2);
        
    }else{
        // no match
        // lets move i forward and check
        int ans1 = solve(i+1,j,s1,s2);

        // lets move j forward and check
        int ans2 = solve(i,j+1,s1,s2);

        ans = max(ans1,ans2);
				
	    if(ans==ans1){
			    recover(i+1,j,s1,s2);
	    }else{
		    recover(i,j+1,s1,s2);
	    }
    }
}


int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    string s1,s2;
    cin >> s1 >> s2;

    memset(dp,-1,sizeof dp);
    
    solve(0,0,s1,s2);
    
    recover(0,0,s1,s2);
    
    cout << result;
    return 0;
}

Now the assignment for you guys is to solve all previousaly solved problems and apply path recovery to them and while solving those u will able to catch the logic behind it . So when i was learning , at that time intially it not making sense but once dry run on one of example then things become clear . So do dry run of example and then u are able to get it.


Converting Recursive Solution Into Tabulation

DP Approaches

In Dyanamic programming (DP) ,we solve problem with -

  1. Breaking a proble into smaller subproblems , then solve that subproblem once .

Recursion : Ek case tum solve kr lo baaki recurison dekh legaa

  1. Store the results (memoization)
  2. Reuse those result when needed

So this 2 approaches also called as-

  1. Memoization ------ TOP DOWN
  2. Tabulation ------ BOTTOM UP
MemoizationTabulation
Starts with original problemStarts with the smaller sub problem(base cases)
Uses recursion to solve smaller subproblemUses iteration/ loops
Store computed resultBuild the table of solutions

Why to use TABULATION over MEMOIZATION

  • Less function -calls / No Recursion stack (Safe from stack overflow)
  • Clear computation order
  • Can reduce memory usages
  • Often better cache performance
  • Even we further space optimised

enter image description here

Golden Framework (Recursion To Tabulation)

  1. Write recursive solution (verify for cases)
  2. Create DP array with Finding the directions of variables (one dimension for each variable state changing )
  3. Write loop or nested loop depened on recusive solution
  4. Copy paste recursive code inside loop 4.1 handle base case 4.2 Instead if making recursive funtional calls get the answer from dp array

Examples Fibonacci number

Recursive code

int fib(int n){
    // base case
    if(n==0)return 0;
    if(n==1)return 1;

    int ans1 = fib(n-1);
    int ans2 = fib(n-2);

    return ans1+ans2;
}

DIRECTIONS : RECURSION :

n = n to 0

TABULATION :

n = 0 to n

Tabulation code

vector<int>dp(n+1,0); // as only 1 variable state which changing

for(int i = 0 ; i <= n ; i++){
    int &ans = dp[i];
    if(i==0){
        ans=0;
        continue; // base case
    }
    if(i==1){
        ans=1;
        continue;// base case
    }

    int ans1 = dp[i-1];
    int ans2 = dp[i-2];
    ans =  ans1+ans2;
}
cout << dp[n]; // we used to call fib(n)

Minimum cost path in grid

Recursive code

int solve(int i,int j,int &n,int &m,vector<vector<int>>&grid){

    //base case

    if(i==n-1 and j==m-1){
        return grid[n-1][m-1];
    }

    if(i>=n or j>=m){
        return INT_MAX;
    }

    // right 
    int ans1 = grid[i][j] + solve(i,j+1,n,m,grid);

    // down
    int ans2 = grid[i][j] + solve(i+1,j,n,m,grid);

    return min(ans1,ans2);
}

DIRECTION : RECURSION :

 i = 0 to n
 j = 0 to m

TABULATION :

 i = n to 0
 j = m to 0

Tabulation code

vector<vector<int>>dp(n+1,vector<int>(m+1));

for(int i = n ; i >= 0 ; i--){
    for(int j = m ; j >= 0 ; j--){

        int &ans = dp[i][j];

        if(i==n-1 and j==m-1){
            ans =  grid[n-1][m-1];
            continue;
        }
        if(i>=n or j>=m){
            ans =  1e16;
            continue;
        }
        
        // right 
        int ans1 = grid[i][j] + dp[i][j+1];

        // down
        int ans2 = grid[i][j] + dp[i+1][j];

        ans =  min(ans1,ans2);
    }
}

cout << dp[0][0] ; // as sovle(0,0)

Now you guys can try solving problem with both approaches which helps to be good at DP .

Every time when you see , try your self and u need to think of how solution works . Then i think you guys on right track to learn dp . Because in general software engineering is about understanding code , system . I hope this will help you to learn about DP .

Written by Manish Patidar

Comments

Loading…
“Man is made by his belief. As he believes, so he is.”_
— Bhagavad Gita