LeetCode_32、53两题(动态规划)
来源:互联网 发布:淘宝回收手机是真的吗 编辑:程序博客网 时间:2024/05/17 21:50
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; }};
- LeetCode_32、53两题(动态规划)
- LeetCode_91、120两题(动态规划)
- LeetCode_338、357两题(动态规划)
- 简单动态规划两题(思想一样)
- DAG上的动态规划两题
- 动态规划两题(矩形嵌套+硬币问题)P161-162
- Leetcode139题Word Break的两种动态规划解法
- 模拟PROBLEM的后面两题 动态规划
- 两道动态规划(DP)题目解析
- 两道动态规划(DP)题目解析
- 动态规划 两序列最近距离(字符串比对)
- UVa437 两种做法(DAG上的动态规划)
- 【Algorithm】动态规划 (1) HDU 动态规划题集
- 动态规划 (1) HDU 动态规划题集
- 动态规划 与两道例题
- 动态规划的两种方式
- 动态规划 HDU 动态规划题集
- 【动态规划(一)】动态规划基础
- xfce4 普通用户登陆不了 -- 解决
- LeetCode 2
- 使用InteIIiJ IDEA开发Java web 项目
- 为什么你的公司整天开会
- ubuntu16.04下面使用graphviz
- LeetCode_32、53两题(动态规划)
- 单元测试(一)-NUnit基础
- 牛客网编程小结(一)——回文序列
- 双链表
- PHP自定义函数99乘法表(正序倒序)
- JavaWeb开发知识总结(Ajax,JSON)
- JMS之——ActiveMQ 高可用与负载均衡集群安装、配置(ZooKeeper + LevelDB + Static discovery)
- 【排序算法】图解算法——用眼睛学习算法
- Gulp新手入门教程 ---- 转