// C++ Program to Print Longest Increasing // Subsequence using Memoization #include…
- User
// C++ Program to Print Longest Increasing // Subsequence using Memoization #include #include using namespace std;
// Helper Recursive Function to Find LIS with Memoization vector findLIS(int idx, int prev_idx, int n, vector& arr, vector<vector<vector>> &memo) {
// Base Case if (idx == n) return {}; // If the current state has already been computed, return the stored result if (!memo[idx][prev_idx + 1].empty()) { return memo[idx][prev_idx + 1]; } // Do not include the current element vector<int> notTake = findLIS(idx + 1, prev_idx, n, arr, memo); // 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, memo); // Insert current element at the beginning take.insert(take.begin(), arr[idx]); } // Choose the better option if (take.size() > notTake.size()) memo[idx][prev_idx + 1] = take; else memo[idx][prev_idx + 1] = notTake; return memo[idx][prev_idx + 1];}
// Function to get Longest Increasing Subsequence with Memoization vector getLis(vector& arr, int n) { // Initialize memo table vector<vector<vector>> memo(n, vector<vector>(n + 1, vector())); return findLIS(0, -1, n, arr, memo); }
int main() { vector arr = {3, 2, 6, 4, 5, 1}; int n = arr.size(); vector lis = getLis(arr, n);
// Print the LIS for(auto num : lis){ cout << num << " "; } return 0;} Time complexity and Space complexity?
- Assistant