首页 > 其他 > 详细

LeetCode-22-Generate Parentheses

时间:2019-01-25 13:32:26      阅读:158      评论:0      收藏:0      [点我收藏+]

算法描述:

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,同时右括号数量不能大于左括号。

    vector<string> generateParenthesis(int n) {
        vector<string> results;
        generate(results, "", 0,0,n);
        return results;
    }
    
    void generate(vector<string>& results, string curr, int left, int right, int n){
        if(curr.size() == 2*n){
            results.push_back(curr);
            return;
        }
        string tmp = "";
        if(left < n){
            tmp = curr +"(";
            generate(results,tmp, left+1, right, n);
        }
        if(right < left){
            tmp = curr + ")";
            generate(results,tmp, left, right+1,n);
        }
        
    }

 

LeetCode-22-Generate Parentheses

原文:https://www.cnblogs.com/nobodywang/p/10319074.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!