longest increaSING SUBsequence single element code example
Example 1: longest common subsequence
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
"""
text1: horizontally
text2: vertically
"""
dp = [[0 for _ in range(len(text1)+1)] for _ in range(len(text2)+1)]
for row in range(1, len(text2)+1):
for col in range(1, len(text1)+1):
if text2[row-1]==text1[col-1]:
dp[row][col] = 1+ dp[row-1][col-1]
else:
dp[row][col] = max(dp[row-1][col], dp[row][col-1])
return dp[len(text2)][len(text1)]
Example 2: longest increasing subsequence techie delight
#include <iostream>
#include <vector>
using namespace std;
void findLIS(int arr[], int n)
{
vector<int> LIS[n];
LIS[0].push_back(arr[0]);
for (int i = 1; i < n; i++)
{
for (int j = 0; j < i; j++)
{
if (arr[j] < arr[i] && LIS[j].size() > LIS[i].size())
LIS[i] = LIS[j];
}
LIS[i].push_back(arr[i]);
}
int j;
for (int i = 0; i < n; i++)
if (LIS[j].size() < LIS[i].size())
j = i;
for (int i : LIS[j])
cout << i << " ";
}
int main()
{
int arr[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };
int n = sizeof(arr)/sizeof(arr[0]);
findLIS(arr, n);
return 0;
}