int fun(int ind,int prev,int n,vector<int>& nums,vector<vector<int>>& dp){ if(ind==n)…
- User
int fun(int ind,int prev,int n,vector& nums,vector<vector>& dp){ if(ind==n) return 0; if(dp[ind][prev+1]!=-1) return dp[ind][prev+1];
int len= 0+fun(ind+1,prev,n,nums,dp); //not take if(prev ==-1 || nums[ind]>nums[prev]){ //take len= max(len,1+ fun(ind+1,ind,n,nums,dp)); } return dp[ind][prev+1]= len; }int lengthOfLIS(vector& nums) { int n= nums.size(); vector<vector>dp(n,vector(n+1,-1)); return fun(0,-1,n,nums,dp); } So this is memoized code for LIS but for length only I want whole lis // 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 {};
// 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();
// Get the LIS using the recursive approach vector<int> lis = getLis(arr, n); for(auto num : lis){ cout << num << " "; } return 0;} This is my recursive code now provide me the code for memoization and take a vector memo keeping variable name and comment same as 2nd code I provided
- Assistant