|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Helper function to calculate the length of the Longest Increasing Subsequence (LIS) |
| 4 | + // using recursion with memoization. |
| 5 | + // Parameters: |
| 6 | + // - nums: The array of numbers. |
| 7 | + // - currIndex: The current index being considered. |
| 8 | + // - prevIndex: The index of the previous element included in the subsequence. |
| 9 | + // - dp: A 2D memoization table to store results of subproblems. |
| 10 | + int solve(vector<int>& nums, int currIndex, int prevIndex, vector<vector<int>>& dp) { |
| 11 | + int n = nums.size(); // Get the size of the array. |
| 12 | + |
| 13 | + // Base case: If we reach the end of the array, return 0. |
| 14 | + if (currIndex == n) return 0; |
| 15 | + |
| 16 | + // Check if the result for the current state is already computed. |
| 17 | + // Note: `prevIndex+1` is used to handle the -1 index case. |
| 18 | + if (dp[currIndex][prevIndex + 1] != -1) return dp[currIndex][prevIndex + 1]; |
| 19 | + |
| 20 | + int include = 0; // Variable to store the result of including nums[currIndex]. |
| 21 | + |
| 22 | + // Check if the current element can be included in the subsequence. |
| 23 | + // It can be included if: |
| 24 | + // - There is no previous element included (prevIndex == -1), OR |
| 25 | + // - The current element is greater than the last included element. |
| 26 | + if (prevIndex == -1 || nums[currIndex] > nums[prevIndex]) { |
| 27 | + include = 1 + solve(nums, currIndex + 1, currIndex, dp); // Include nums[currIndex]. |
| 28 | + } |
| 29 | + |
| 30 | + // Exclude the current element and move to the next. |
| 31 | + int exclude = solve(nums, currIndex + 1, prevIndex, dp); |
| 32 | + |
| 33 | + // Store the result in the memoization table and return it. |
| 34 | + return dp[currIndex][prevIndex + 1] = max(include, exclude); |
| 35 | + } |
| 36 | + |
| 37 | + // Main function to calculate the length of the Longest Increasing Subsequence (LIS). |
| 38 | + int lengthOfLIS(vector<int>& nums) { |
| 39 | + int n = nums.size(); // Get the size of the array. |
| 40 | + |
| 41 | + // Initialize a 2D DP table with -1 to indicate uncomputed states. |
| 42 | + // Dimensions are n x (n+1) to handle the case where prevIndex == -1. |
| 43 | + vector<vector<int>> dp(n, vector<int>(n + 1, -1)); |
| 44 | + |
| 45 | + // Start the recursion from the first element with no previous element (-1). |
| 46 | + return solve(nums, 0, -1, dp); |
| 47 | + } |
| 48 | +}; |
0 commit comments