您的位置:首页 > 其它

LeetCode_32、53两题(动态规划)

2017-05-21 22:19 295 查看
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: