求出最长好子序列 I

求出最长好子序列 I

题面:https://leetcode.cn/problems/find-the-maximum-length-of-a-good-subsequence-i/description/

dp含义:

dp[i][j] 前i个数,不超过j个不满足

递推:

遍历之前的数,如果nums[l]==nums[i],那么
dp[i][j]=max(dp[i][j],dp[l][j]+1)
否则
dp[i][j]=max(dp[i][j],dp[l][j-1]+1)

初始化:

最开始最长都是1;

遍历顺序

从1到n

code:

public:
    int maximumLength(vector<int>& nums, int k) {
        int n = nums.size();  
        vector<vector<int>> dp(n, vector<int>(k + 1, 1));   //dp[i][j]表示
        for (int i = 1; i < n; i++) {
            for (int j = 0; j <=k; j++) {
                for (int l = 0; l < i; l++) {
                    if (nums[i] == nums[l]) {
                        dp[i][j] = max(dp[i][j], dp[l][j] + 1);  
                    } else if (j > 0) {
                        dp[i][j] = max(dp[i][j], dp[l][j - 1] + 1);
                    }
                }
            }
        }
        int ma = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j <= k; j++) {
                if (dp[i][j] > ma) ma = dp[i][j];
            }
        }
        return ma;
    }
};
posted @ 2024-06-10 10:58  lelemeimei  阅读(32)  评论(0编辑  收藏  举报