简体   繁体   English

最长递增子序列。 为什么 topDown 代码不起作用?

[英]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. Q. 给定一个整数数组 nums,返回最长严格递增子序列的长度。

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].例如,[3,6,2,7] 是数组 [0,3,1,6,2,2,7] 的子序列。

Example 1:示例 1:

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

Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.解释:最长的递增子序列为[2,3,7,101],因此长度为4。

Answer:回答:

My recursion code is working correct but TopDown DP code is not working.我的递归代码工作正常,但 TopDown DP 代码不工作。 Even I am just storing the correct answers in dp vector and use them again.即使我只是将正确答案存储在 dp 矢量中并再次使用它们。

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.基本上你想用 dp 来记忆。 I would suggest taking a 2d vector for memoization in this case.在这种情况下,我建议使用 2d 向量进行记忆。

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.这个概念和你的一样,我刚刚使用了一个 2d 矢量 dp。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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