zoukankan      html  css  js  c++  java
  • 【LeetCode】22. Generate Parentheses (2 solutions)

    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:

    "((()))", "(()())", "(())()", "()(())", "()()()"

    解法一:递归

    借助栈,'('、')'构成一对分别进出栈。最后栈为空,则输入括号构成的字符串是合法的。

    注意:调用top()前先check一下栈是否为空

    class Solution {
    public:
        vector<string> generateParenthesis(int n) {
            vector<string> result;
            if(n == 0)
                return result;
            //first must be '('
            string cur = "(";
            stack<char> s;
            s.push('(');
            
            Helper(result, cur, s, 2*n-1);
            return result;
        }
        void Helper(vector<string>& result, string cur, stack<char> s, int num)
        {
            if(num == 1)
            {//must be ')'
                if(s.top() == '(' && s.size() == 1)
                {//all matched
                    cur += ')';
                    result.push_back(cur);
                }
            }
            else
            {
                //'(' always push
                string str1 = cur;
                str1 += '(';
                s.push('(');
                Helper(result, str1, s, num-1);
                s.pop();
                
                //')'
                if(!s.empty())
                {//prune. never begin with ')'
                    string str2 = cur;
                    str2 += ')';
                    if(s.top() == '(')
                        s.pop();    //check empty() before access top()
                    else
                        s.push(')');
                    Helper(result, str2, s, num-1);
                }
            }
        }
    };

    解法二:递归

    稍作分析可知,栈是不必要的,只要记录字符串中有几个'(',记为count。

    每进入一个'(', count ++. 每匹配一对括号, count--。

    最终全部匹配,需要count==0

    class Solution {
    public:
        vector<string> generateParenthesis(int n) {
            vector<string> ret;
            string cur = "(";
            gen(ret, cur, 2*n-1, 1);
            return ret;
        }
        void gen(vector<string>& ret, string cur, int k, int count)
        {
            if(k == 1)
            {//last paretheses
                if(count == 1)
                {//one unmatched '('
                    cur += ')';
                    ret.push_back(cur);
                }
            }
            else
            {
                if(count >= 0)
                {//either '(' or ')' 
                    //'('
                    count ++;
                    if(count <= k-1)
                    {//otherwise, all ')'s are still not enough
                        cur += '(';
                        gen(ret, cur, k-1, count);
                        cur.erase(cur.end()-1);
                    }
                    count --;
                    
                    //')'
                    if(count > 0)
                    {
                        count --;
                        cur += ')';
                        gen(ret, cur, k-1, count);
                        cur.erase(cur.end()-1);
                        count ++;
                    }
                }
            }
        }
    };

  • 相关阅读:
    (一)jQuery EasyUI 的EasyLoader载入原理
    java playframework
    android Handlerr.removeCallbacksAndMessages(null)的妙用
    云已成为一种趋势,大有可为
    将一个4X4的数组进行逆时针旋转90度后输出,要求原数组数据随机输入
    小强的HTML5移动开发之路(40)——jqMobi中实践header定义的几种方式
    AngularJS中的依赖注入
    极光消息推送服务器端开发实现推送(下)
    用CSS指定外部链接的样式
    版本控制(1)——SVN
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/4175159.html
Copyright © 2011-2022 走看看