classSolution {public:intfind_ans(vector<int>& nums,int index,int prev,vector<vector<int>> &dp){if(index<0)return0;if(dp[index][prev] !=-1)returndp[index][prev];int not_take =find_ans(nums, index-1, prev, dp);int take =0;if(prev ==nums.size() ornums[index] <nums[prev]){ take =1+find_ans(nums, index-1, index, dp); }returndp[index][prev] =max(take, not_take); }intlengthOfLIS(vector<int>& nums) {int n =nums.size();int prev =-1; vector<vector<int>>dp(n,vector<int>(n+1,-1));returnfind_ans(nums, n-1, n, dp); }};
Approach 2:
New Solution:
dp[i] represnts longest LIS count until index i
Go N^2 and check for all prevs before and add if less
Refer Stiver Video for more clarity
Printing LIS
Slight modification to above code
Maintain hash containing info for backtracking
Basically,
When you get updation in dp array, means you got big LIS
Update in hash array as the index which gave that updation
So that when you finish, You will have a lastindex,
with which you can backtrack till the end