The 10 most important DP questions
Oct 16, 2020
Let's solve them, here is the list.
- Longest Common Subsequence
- Shortest Common Supersequence
- Longest Increasing Subsequence problem
- The Levenshtein distance (Edit distance) problem
- Matrix Chain Multiplication
- 0–1 Knapsack problem
- Partition problem
- Rod Cutting
- Coin change problem
- Word Break Problem
- LONGEST COMMON SUBSEQUENCE
Understanding the question:
for each letter, we will check whether this letter equals to the letter in the other string, if so we will take it, otherwise, we will continue advancing with one of the strings
// Method1()- recursive solution(Top- down approach)
// time complexity - O(2^(m+n))
// space complexity - O(m+n)
public static int LCSM1(char[] X, char[] Y, int i, int j) {
if (i <= 0 || j <= 0)
return 0;
if (X[i - 1] == Y[j - 1])
return 1 + LCSM1(X, Y, i - 1, j - 1);
else
return Math.max(LCSM1(X, Y, i, j - 1), LCSM1(X, Y, i - 1, j));}
we can use memoization
public static int LCSM2(char[] X, char[] Y, int i, int j, int[][] dp) {
if (i <= 0 || j <= 0)
return 0;
if (dp[i][j] != 0)
return dp[i][j];
if (X[i - 1] == Y[j - 1])
return 1 + LCSM2(X, Y, i - 1, j - 1, dp);
else
return dp[i][j] = Math.max(LCSM2(X, Y, i, j - 1, dp), LCSM2(X, Y, i - 1, j, dp));
}