Dynamic Programming

5. Longest Palindromic Substring


Given a string S, find the longest palindromic substring in S. You may assume that the maximum length ofS is 1000, and there exists one unique longest palindromic substring.

字符串经典题目,考虑用DP解决。布尔数组dp[i][j]表示从s[i]到s[j]是否为回文子串,dp[i][i]=true,dp[i][i+1]=(s[i]==s[i+1]),递推公式为dp[i][j]=(dp[i+1][j-1] && s[i]==s[j])。递推时用start存储子串起始位置,maxlength存储子串长度。

class Solution {
public:
    string longestPalindrome(string s) {
        const int length=s.size();
        int maxlength=1;
        int start=0;
        bool dp[1000][1000]={false};
        for(int i=0;i<length;i++)
        {
            dp[i][i]=true;
            if(i<length-1&&s[i]==s[i+1])
            {
                dp[i][i+1]=true;
                start=i;
                maxlength=2;
            }
        }
        for(int len=3;len<=length;len++)
            for(int i=0;i<=length-len;i++)
            {
                int j=i+len-1;
                if(dp[i+1][j-1]&&s[i]==s[j])
                {
                    dp[i][j]=true;
                    maxlength=len;
                    start=i;
                }
            }
        if(maxlength>=2)
            return s.substr(start,maxlength);
        return s.substr(start,1);
    }
};


10. Regular Expression Matching


Implement regular expression matching with support for '.' and '*'.

'.' Matches any single character.
'*' Matches zero or more of the preceding element.

The matching should cover the entire input string (not partial).

The function prototype should be:
bool isMatch(const char *s, const char *p)

Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true
首先想到用递归求解,思路是先考虑p[1]是否等于'*',p[1]!='*'时,如果s[0]==p[0]或p[0]='.',表明s和p的第1位匹配,递归搜索下一位,否则返回false;p[1]=='*'时,p[1]可以匹配s中连续的0个或多个等于p[0]的字符,依次递归搜索即可。注意,如果s[0]与p[0]一开始就不匹配,则递归调用isMatch(s,p.substr(2)),表示跳过p中*之前的字符和*,从*之后开始重新匹配。

class Solution {
public:
    bool isMatch(string s, string p) {
        if(p.empty()) return s.empty();
        if('*'!=p[1]){
            if(s[0]==p[0] || (p[0]=='.' && !s.empty()))
                return isMatch(s.substr(1),p.substr(1));
            return false;
        }
        else{
            while(s[0]==p[0] || (p[0]=='.' && !s.empty())){
                if(isMatch(s,p.substr(2)))
                    return true;
                s=s.substr(1);
            }
            return isMatch(s,p.substr(2));
        }
    }
};

然而递归调用开销较大,可以尝试DP求解,时间复杂度与空间复杂度均为O(n^2)。res[i][j]表示s中前i个字符与p中前j个字符是否匹配,同样根据p[j-1]是否等于'*'进行分类。

class Solution {
public:
    bool isMatch(string s, string p) {
        vector<vector<bool>> res(s.size()+1,vector<bool>(p.size()+1,false));
        res[0][0]=true;
        for(int i=1;i<=s.size();i++){
            res[i][0]=false;
        }
        for(int j=1;j<=p.size();j++){
            res[0][j]=j>1 && '*'==p[j-1] && res[0][j-2];
        }
        for(int i=1;i<=s.size();i++){
            for(int j=1;j<=p.size();j++){
                if(p[j-1]!='*'){
                    res[i][j]=res[i-1][j-1] && (s[i-1]==p[j-1] || '.'==p[j-1]);
                }else{
                    res[i][j]=res[i][j-2] || (s[i-1]==p[j-2] || '.'==p[j-2]) && res[i-1][j];
                }
            }
        }
        return res[s.size()][p.size()];
    }
};

53. Maximum Subarray


Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.

求最大子序列和。《编程珠玑》上有详细分析,暴力搜索时间复杂度O(n^3),改进后O(n^2),归并时间复杂度O(nlog n),dp扫描O(n)。dp状态转移方程为dp[i]=max(dp[i-1]+sum[i],sum[i])。这种情况下默认子序列必须存在,即不能取空集使返回结果为0。当可取空集时,转移方程为dp=max(dp[i-1]+sum[i],0)。由于dp是动态更新,不断覆盖的,可以只用一个dp变量存储当前位置最大值,从而减小空间复杂度。

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int dp=nums[0],answer=nums[0];
        for(int i=1;i<nums.size();++i){
            dp=max(dp+nums[i],nums[i]);
            answer=max(answer,dp);
        }
        return answer;
    }
};






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值