Parentheses(圓括號)匹配與生成

20. Valid Parentheses合法括號

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

分析:本題構造一個棧,open括號進棧,close括號檢查棧是否非空且棧頂元素爲對應的open符號,否則返回false,結束後若棧空返回true。

class Solution {
public:
    bool isValid(string s) {
        int l = s.size();
        stack<char> st;
        for(int i=0;i<l;i++)
        {
            char c = s[i];
            if(c=='('  || c=='[' || c=='{')
                st.push(c);
            else
            {
                if(st.empty())
                    return false;
                if(c==')')
                    if(st.top() == '(')
                        st.pop();
                    else
                        return false;
                else if(c==']')
                    if(st.top() == '[')
                        st.pop();
                    else
                        return false;
                else if(c=='}')
                    if(st.top() == '{')
                        st.pop();
                    else
                        return false;
            }
        }
        if(st.empty())
            return true;
        return false;
 
    }
};

22. Generate Parentheses生成括號

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

分析:本題可使用回溯法解決,回溯法其實就是DFS加剪枝,這裏我們添加兩個剪枝條件:

1.先嚐試添加左括號,如果左括號數目小於n

2.再嘗試添加右括號數目,如果右括號數目小於當前左括號數目

所以我們的回溯函數有五個參數,分別爲:ans,當前string,left數目,right數目,n

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> ans;
        backtrack(ans,"",0,0,n);
        return ans;
        
    }
    void backtrack(vector<string> &ans, string cur, int left, int right,int max)
    {
        if(cur.size()==max*2)
        {
            ans.push_back(cur);
            
            return;
        }
        if(left<max)
            backtrack(ans,cur+'(',left+1,right,max);
        if(right<left)
            backtrack(ans,cur+')',left,right+1,max);
    }
};

 

發佈了9 篇原創文章 · 獲贊 26 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章