zoukankan      html  css  js  c++  java
  • 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:

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


    思路:深度优先搜索

    本体思路:深搜+动态规划

    具体过程:首先判断右边是否到3,到3立即保存,然后深搜,如果没有,立即直到最底层,然后退出,看是否左边大于右边,如果是,加右括号

    “((()))” — “(()())”—”(())()”— “()(())” — “()()()”

    的确有些难以理解


    代码:

    class Solution {
    public:
    //https://leetcode.com/problems/generate-parentheses/
        void parensHelper(int left,int right,int n,vector<string>&result,string temp){
            if(right==n){
                //右边等于n说明满了,插入temp,返回
                result.push_back(temp);
                return;
            }
            
            if(left<n){
                //深度优先
                temp+='(';
                parensHelper(left+1,right,n,result,temp);
                temp.pop_back();
            }
            //到现在,尽管dfs题目做的很少,但是发现每每深度优先搜索之后,一定有“出栈”,方便下一个入口函数
            if(left>right){
                temp+=')';
                parensHelper(left,right+1,n,result,temp);
                temp.pop_back();
            }
        }       //      ( ( ( ) ) ) -- ( ( ( ) ) ) -- 
    
        vector<string> generateParenthesis(int n) 
        {
            string temp;
            vector<string> result;
            parensHelper(0,0,n,result,temp);
            return result;
        }    
    };


  • 相关阅读:
    入门训练 圆的面积
    入门训练 序列求和
    interface
    Horizon
    H903
    Sphinx Building Docs in horizon
    Cinder Columns
    DevStack添加Swift
    Murano py27和py34的兼容处理
    Murano Weekly Meeting 2015.12.01
  • 原文地址:https://www.cnblogs.com/jsrgfjz/p/8519907.html
Copyright © 2011-2022 走看看