[Code Random Record] Day52 Dynamic Planning 13

first question

 LeetCode official website - the technology growth platform loved by geeks around the world

dp[i]: The length of the longest increasing subsequence ending with nums[i]

Recursion formula: dp[i] = max(dp[j] +1,dp[i]) 

Question 3

LeetCode official website - the technology growth platform loved by geeks around the world

 Create a two-dimensional DP array, row i is nums1, column j is nums2, dp[i][j] represents the subsequence length of nums1[i-1] and nums[j-1] is the mantissa, because here it represents i- 1 and j-1, so when constructing dp, one more bit must be constructed so that it can be equal to size() during for traversal. The common subsequences of nums1 and nums2 must advance and retreat at the same time, so only when nums1[i-1 ] == nums2[j-1], only update dp[i][j]:

class Solution {
public:
    int findLength(vector<int>& nums1, vector<int>& nums2) {
        vector<vector<int>> dp(nums1.size()+1, vector<int>(nums2.size()+1, 0));
        int res = 0;
        for (int i = 1 ; i <= nums1.size(); i++) {
            for (int j = 1; j <= nums2.size(); j++) {
                if (nums1[i - 1] == nums2[j - 1]) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                }
                if (dp[i][j] > res) res = dp[i][j];
            }
        }
        return res;

    }
};

Guess you like

Origin blog.csdn.net/weixin_43785314/article/details/132677624