经典DP问题:最长递增子序列和最长公共子序列

69 篇文章 0 订阅
44 篇文章 0 订阅

LIS问题:最长递增子序列(Longest Increasing Subsequence);
LCS问题:最长公共子序列(Longest Common Subsequence);

子序列(subsequence)和子串(substring)的概念:子序列不要求连续,而子串必须由连续的字符组成。

LIS问题

时间复杂度:O(n^2);
空间复杂度:O(n);
设置一个DP数组,维护每个位置的符号作为结尾的最小的序列长度;

class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        int numsLen = nums.size();
        vector<int> L(numsLen, 1);
        for (int i = 1; i < numsLen; ++i) {
            for (int j = 0; j < i; ++j) {
                if (nums[j] < nums[i] && L[j] + 1 > L[i]) L[i] = L[j] + 1;
            }
        }

        int maxLengthofSubsequence = 0;
        for (int i = 0; i < numsLen; ++i) {
            maxLengthofSubsequence = max(maxLengthofSubsequence, L[i]);
        }
        return maxLengthofSubsequence;
    }
};

LCS问题

LCS问题中因为会面临着子串长度不同的问题,所以需要使用一个二维DP数组。
时间复杂度:O(m * n);
空间复杂度:O(m * n);
m和n分别是字符串text1和字符串text2的长度。

// 经典二维DP

class Solution {
public:
    int longestCommonSubsequence(string text1, string text2) {
        int text1Len = text1.length(), text2Len = text2.length();
        vector<vector<int>> dp(text1Len + 1, vector<int>(text2Len + 1)); // 建立二维DP数组
        for (int i = 0; i <= text2Len; ++i) { // 初始化DP的数组的初始条件
            dp[0][i] = 0;
        }
        for (int i = 0; i <= text1Len; ++i) {
            dp[i][0] = 0;
        }

        int maxLCSLen = 0;
        for (int i = 1; i <= text1Len; ++i) { // 自底向上DP
            for (int j = 1; j <= text2Len; ++j) {
                if (text1[i - 1] == text2[j - 1]) dp[i][j] = 1 + dp[i - 1][j - 1]; // 分两种情况,一种是最后一个字符相等,一种是最后一个字符不相等
                else dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
                maxLCSLen = max(maxLCSLen, dp[i][j]);
            }
        }
        return maxLCSLen;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值