zoukankan      html  css  js  c++  java
  • 22.Generate Parentheses (String; Back-Track)

    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:

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

    思路:两个递归函数,互相调用

    class Solution {
    public:
        vector<string> generateParenthesis(int n) {
            if(n==0) return ret;
            
            dfsLeft("",0,0,n);
            return ret;
        }
        
        void dfsLeft(string s, int depthLeft, int depthRight, int n){ //add one left parenthesis
            if(depthLeft >= n){ //end left
                return;
            }
            else{
                s += '(';
                depthLeft++;
                dfsRight(s,depthLeft, depthRight, n);
                dfsLeft(s,depthLeft, depthRight, n);
            }
        }
       
        void dfsRight(string s, int depthLeft, int depthRight, int n){ //add one right parenthesis
            if(depthRight >= n){ //end all
                ret.push_back(s);
            }
            else if(depthRight >= depthLeft){ //end right
                return;
            }
            else{
                s += ')';
                depthRight++;
                dfsLeft(s,depthLeft, depthRight, n);
                dfsRight(s,depthLeft, depthRight, n);
            }
        }
    private:
        int len;
        vector<string> ret;
    
    };

    更简洁的写法:

    class Solution {
    public:
        vector<string> generateParenthesis(int n) {
            if(n == 0) return ret;
            
            len = n*2;
            dfsLeft(n, 0, "");
            return ret;
        }
        
        void dfsRight(int lNum, int rNum, string str){//add right parenthese
            while(rNum){ 
                str += ')';
                dfsLeft(lNum, --rNum, str);
            }
            if(str.length() == len){
                ret.push_back(str);
            }
        }
        
        void dfsLeft(int lNum, int rNum, string str){//add left parenthese
            while(lNum){
                str += '(';
                dfsRight(--lNum, ++rNum, str);
            }
        }
    private:
        int len;
        vector<string> ret;
    
    };
  • 相关阅读:
    Java-01,计算1-10的阶乘之和
    软件工程研究生面试机试考题-2018
    nginx会话保持之sticky模块
    Dubbo原理简介、与Zookeeper整合利用
    Day41 openstack基础
    krb5-libs这个RPM包删掉了导致ssh无法连接
    day40 数据结构-算法(二)
    进程上下文频繁切换导致load average过高
    day39 算法基础
    应用性能管理工具PinPoint介绍
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4705551.html
Copyright © 2011-2022 走看看