LeetCode-20、22:Valid、Generate 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:
  • Open brackets must be closed by the same type of brackets.
  • 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

    Example 4:
    Input: "([)]"
    Output: false

    Example 5:
    Input: "{[]}"
    Output: true

    問題解決:
    「(',')」,「{','}','[,']」のみを含む文字列を与え,文字列が有効であるか否かを判断する.
    リンク:
  • LeetCode:https://leetcode.com/problems/valid-parentheses/description/

  • 構想ラベル
    アルゴリズム:スタック構造
    回答:
  • は、スタックが空であるかどうか、または右記号がスタックトップとペアを組むことができるかどうかを判断する.
  • class Solution {
    public:
        bool isValid(string s) {
            stack<char> paren;
            for (char& c : s) {
                switch (c) {
                    case '(': 
                    case '{': 
                    case '[': paren.push(c); break;
                    case ')': if (paren.empty() || paren.top()!='(') return false; else paren.pop(); break;
                    case '}': if (paren.empty() || paren.top()!='{') return false; else paren.pop(); break;
                    case ']': if (paren.empty() || paren.top()!='[') return false; else paren.pop(); break;
                    default: ; // pass
                }
            }
            return paren.empty() ;
        }
    };

    タイトル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:
    [
      "((()))",
      "(()())",
      "(())()",
      "()(())",
      "()()()"
    ]

    問題解決:
    nは括弧を生成する対数を表します.可能なすべての有効な括弧の組み合わせを生成できるように関数を書いてください.
    リンク:
  • LeetCode:https://leetcode.com/problems/generate-parentheses/description/

  • 構想ラベル
    アルゴリズム:再帰、DFS
    回答:
  • 題目規則によれば,記号は2つの「(」,「)」のみであり,それぞれその個数を左かっこleftと右かっこrightと記すので,条件を満たす組合せはleft<=rightに違いない.そうでなければ、要求に合わない.
  • 同時に、leftとrightがともに0の場合、現在の組合せは条件を満たす.
  • class Solution {
    public:
        vector<string> generateParenthesis(int n) {
            vector<string> res;
            generateParenthesisDFS(n, n, "", res);
            return res;
        }
    
        void generateParenthesisDFS(int left, int right, string out, vector<string> &res){
            if(left > right)
                return;
            if(left == 0 && right == 0)
                res.push_back(out);
            else{
                if(left > 0) generateParenthesisDFS(left-1, right, out+'(', res);
                if(right > 0) generateParenthesisDFS(left, right-1, out+')', res);
            }
        }
    };

    テーマ: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:
    [
      "((()))",
      "(()())",
      "(())()",
      "()(())",
      "()()()"
    ]

    問題解決:
    nは括弧を生成する対数を表します.可能なすべての有効な括弧の組み合わせを生成できるように関数を書いてください.
    リンク:
  • LeetCode:https://leetcode.com/problems/generate-parentheses/description/

  • 構想ラベル
    アルゴリズム:再帰、DFS
    回答:
  • 題目規則によれば,記号は2つの「(」,「)」のみであり,それぞれその個数を左かっこleftと右かっこrightと記すので,条件を満たす組合せはleft<=rightに違いない.そうでなければ、要求に合わない.
  • 同時に、leftとrightがともに0の場合、現在の組合せは条件を満たす.
  • class Solution {
    public:
        vector<string> generateParenthesis(int n) {
            vector<string> res;
            generateParenthesisDFS(n, n, "", res);
            return res;
        }
    
        void generateParenthesisDFS(int left, int right, string out, vector<string> &res){
            if(left > right)
                return;
            if(left == 0 && right == 0)
                res.push_back(out);
            else{
                if(left > 0) generateParenthesisDFS(left-1, right, out+'(', res);
                if(right > 0) generateParenthesisDFS(left, right-1, out+')', res);
            }
        }
    };