1. 程式人生 > >LeetCode_32、53兩題(動態規劃)

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;
    }
};