简体   繁体   中英

Longest Increasing Subsequence. Why topDown code is not working working?

Q. Given an integer array nums, return the length of the longest strictly increasing subsequence.

A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].

Example 1:

Input: nums = [10,9,2,5,3,7,101,18]
Output: 4

Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.

Answer:

My recursion code is working correct but TopDown DP code is not working. Even I am just storing the correct answers in dp vector and use them again.

Recursion code:

int lengthOfLIS(vector<int>& arr, int i=0, int prev= INT_MIN){
        //........... base case............
        if(i==arr.size()) return 0;
        //........... recursive case...........
        // take if it is grater than prev
        int X = INT_MIN;
        if(arr[i] > prev)
            X = 1 + lengthOfLIS(arr, i+1, arr[i]);
        // ignore
        int Y = lengthOfLIS(arr, i+1, prev);
    
        return max(X, Y);
    }


TopDown DP code:- 

int sol(vector<int> arr, vector<int>& dp, int i=0, int prev= INT_MIN){
        //........... base case............
        if(i==arr.size()) return dp[i]=0;
        if(dp[i]!=-1) return dp[i];
        //........... recursive case...........
        // take if it is grater than prev
        int X = INT_MIN;
        if(arr[i] > prev)
            X = 1 + sol(arr, dp, i+1, arr[i]);
        // ignore
        int Y = sol(arr, dp, i+1, prev);
    
        return dp[i] = max(X, Y);
    }

Basically you want to memoize using dp. I would suggest taking a 2d vector for memoization in this case.

So the final solution will be :

int lengthOfLIS(vector& nums){

int n=nums.size();

vector<vector<int>> dp(n,vector<int>(n+1,-1));
 
return sol(nums,0,n,-1,dp);

}

int sol(vector<int>& nums,int i,int n,int prev,vector<vector<int>>& dp){

if(i==n){
    return 0;
} 

if(dp[i][prev+1]!=-1){
    
    return dp[i][prev+1];
    
}

int X=0;int Y=0;
      
if(prev==-1 or nums[i]>nums[prev]){
    
    X=1+sol(nums,i+1,n,i,dp);
    
}

Y=sol(nums,i+1,n,prev,dp);
   
dp[i][prev+1]=max(X,Y);

return dp[i][prev+1];

}   
};

The concept is the same as yours, I have just used a 2d vector dp.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM