LeetCode_32、53两题(动态规划)

LeetCode_32. Longest Valid Parentheses
原题:
Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.
For “(()”, the longest valid parentheses substring is “()”, which has length = 2.
Another example is “)()())”, where the longest valid parentheses substring is “()()”, which has length = 4.
解析:判断有最长的有效括号子串是多长,何为一个连续有效的括号字串呢?比如:
()(()),()(),(())
这种类型可以用动态规划来做,对字符串里的每个元素,求出以它本身结尾的最长有效字串是多长(若自身不能作为结尾则是0),最后筛选出最长的那段字串长度即可。所以对每个元素我们有2种类型,一种是‘(’,另一种是‘)’,对于前者,我们每次遇到它的时候用栈将它的位置push进栈里,对于后者,我们知道若以他结尾必须要有一个‘(’与之对应,若栈不为空,则有对应,并且以它结尾的最长字串长度 = 前一个元素结尾的最长字串长度 + 2 + 对应‘(’前一个元素结尾的最长字串长度(因为可能连续比如”()()”)。
具体代码如下:

class Solution {
public:
    int longestValidParentheses(string s) {
        stack<int> st;
        int size = s.size();

        vector<int> len(size);


        for(int i = 0;i < size;i ++){
            if(s[i] == '('){
                st.push(i);
                len[i] = 0;
            }
            else{
                if(st.empty())len[i] = 0;
                else{
                    if(st.top() - 1 >= 0)len[i] = 2 + len[i-1] + len[st.top() - 1];
                    else len[i] = 2 + len[i-1];
                    st.pop();
                }

            }
        }

        int maxlen = 0;
        for(int i = 0;i < size;i ++){
            maxlen = max(maxlen,len[i]);
        }
        return maxlen;
    }

};

LeetCode_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.
解析:
和上一题同一种方法,对每个元素,找到以它结尾的最大的和,最后再综合找出最大的那个。所以对每个元素,以它为结尾的最大和只有两种情况,一种就是只是它本身,另一种就是它与前面一个元素结尾的最大和之和。具体代码如下,清晰明了:

class Solution {
public:
    int maxSubArray(vector<int>& nums) {

        if(nums.empty())return 0;
        int size = nums.size();
        if(size == 1)return nums[0];
        vector<int> maxsum(size);
        maxsum[0] = nums[0];
        for(int i = 1;i < size;i ++){
            maxsum[i] = max(nums[i],maxsum[i-1] + nums[i]);
        }
        int getmax = maxsum[0];
        for(int i = 1;i < size;i ++){
            getmax = max(maxsum[i],getmax);
        }
        return getmax;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值