zoukankan      html  css  js  c++  java
  • 22. Generate Parentheses

    Problem statement:

    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:

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

    Analysis:

    This problem also involves DFS, but is different with the DFS template I have summarized, it belongs to the questions that just given a number and find some possible solutions. It does not belong to the problems which relate to an array or string. This is a new DFS philosophy, but it looks simple.

    Some key points of this problem:

    All possible solutions: DFS without a return value.

    n is the given number: it is the terminate condition of DFS meanwhile we also need to add one possible solution.

    I struggled for how to orderly arrange "(" and ")", but when I checked the answer, I found that this is not what we need to care, we need to check that in each loop, the number of "(" should always be greater or equal than the number of ")". This is another terminate condition, but no any action for the answer.

    Solution:

    class Solution {
    public:
        vector<string> generateParenthesis(int n) {
            vector<string> sets;
            generate_parenthesis(sets, "", n, n);
            return sets;
        }
    private:
        void generate_parenthesis(vector<string>& sets, string seq, int left, int right){
            // minus 1 each time when a "(" or ")" is add
            // so left should always less than right
            if(left  >  right){
                return;
            }
            if(left == 0 && right == 0){
                sets.push_back(seq);
                return;
            }
            // add "("
            if(left > 0){
                generate_parenthesis(sets, seq + "(", left - 1, right);
            }
            // add ")"
            if(right > 0){
                generate_parenthesis(sets, seq + ")", left, right - 1);
            }
            return;
        }
    };
  • 相关阅读:
    基于RockMq 实现分布式事务
    开机启动脚本编写
    JS 校验笔记
    git 小计
    EasyExcel简单导入示例
    vue的rule中使用validator(异步请求)验证
    字符串、数值、布尔值、函数参数的解构赋值以及圆括号问题
    对象解构赋值
    数组的解构赋值与yield
    window10的cmd重置子系统ubuntu用户密码以及ubuntu设置密码切换用户
  • 原文地址:https://www.cnblogs.com/wdw828/p/6844681.html
Copyright © 2011-2022 走看看