// C++ Program to Print Longest Increasing // Subsequence using a Recursive Naive…
- User
// C++ Program to Print Longest Increasing // Subsequence using a Recursive Naive Approach
#include #include using namespace std;
// Helper Recursive Function to Find LIS vector findLIS(int idx, int prev_idx, int n, vector& arr) {
// Base Case if (idx == n) return {};
code// Do not include the current element vector<int> notTake = findLIS(idx + 1, prev_idx, n, arr); // Include the current element // if it's greater than the previous element vector<int> take; if (prev_idx == -1 || arr[idx] > arr[prev_idx]) { take = findLIS(idx + 1, idx, n, arr); // Insert current element at the beginning take.insert(take.begin(), arr[idx]); } if (take.size() > notTake.size()) return take; else return notTake;}
// Function to get Longest Increasing Subsequence vector getLis(vector& arr, int n) { return findLIS(0, -1, n, arr); }
int main() { vector arr = {3, 2, 6, 4, 5, 1}; int n = arr.size();
code// Get the LIS using the recursive approach vector<int> lis = getLis(arr, n); for(auto num : lis){ cout << num << " "; } return 0;} Do it using memoization by taking a memo 2d array
- Assistant