leetcode2

本文深入探讨并解析了一系列复杂的算法和技术应用,包括但不限于DP、贪心算法、递归优化等核心概念及其实际应用场景。文章详细阐述了如何解决长有效括号子串问题和跳跃数组最小跳跃次数问题,并提供了独特的解决思路和优化方法。通过实例分析,读者能够掌握算法的核心逻辑,提升解决实际问题的能力。

今天闲来无事又刷了几道。

 

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.

class Solution {
public:
    int longestValidParentheses(string &s) {
        if (s == "") return 0;
        int cnt = 0;
        int totr = 0;
        int lastValid = -1;
        for (int i = 0;i < s.length();i++)
        {
            if (s[i] == ')') totr++;
            cnt += (s[i] == '(' ? 1:-1);
            if (cnt < 0) 
            {
                if (i+1 < s.length())
                {
                    s = s.substr(i+1,s.length()-i-1);
                    return max(i,longestValidParentheses(s));
                }
                else return i;
            }
            if (cnt == 0) lastValid = i;
        }
        
        if (lastValid > 0)
        {
            s = s.substr(lastValid+1,s.length()-lastValid-1);
            for (auto& x : s) x = (x=='('?')':'(');
            reverse(s.begin(),s.end());
            return max(longestValidParentheses(s),lastValid + 1);
        }
        else
        {
            for (auto& x : s) x = (x=='('?')':'(');
            reverse(s.begin(),s.end());
            return longestValidParentheses(s);
        }
    }
};

只能说,我想歪了。这是道简单的DP,中间还WA了很多次。

我这个神奇的做法也是醉了。

比较需要引起注意的是,递归当中,如果带着数组字符串之类的,如果没有&,很容易MLE。

标准的做法是 f[i] 表示 i 结尾最长的合法序列,

如果(结尾, 0

如果()结尾, f[i-2]+2

如果))结尾, s[i - f[i-1] - 1]=='(' 的情况下 f[i-f[i-1]-2]+f[i-1]+2

 

11.17

想多了

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

贪心

class Solution {
public:
    int jump(vector<int>& a) {
        int cl = 0;
        int cr = 0;
        int steps = 0;
        while (cl <= cr && cr < a.size() - 1)
        {
            int nr = cr;
            for (int i = cl;i<=cr;i++) nr = max(nr,i+a[i]);
            steps++;
            cl = cr+1;
            cr = nr;
        }
        return steps;
    }
};

 

转载于:https://www.cnblogs.com/soya/p/4915580.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值