码迷,mamicode.com
首页 > 其他好文 > 详细

22. Generate Parentheses

时间:2017-01-04 23:30:35      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:air   key   flow   str   public   附加   ase   out   uri   

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:

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

分析

罗列出所有的可能,类似于排列组合,可以使用DFS来做

l 记录剩余 ‘(‘ 数量
r 记录可以添加的 ‘)‘ 数量
只有当附加一个 ‘(‘ 后,才可以附加 ‘)‘.

计数原则是:
初始时,l = n, r = 0.
str添加一个 ‘(‘, 则 l 减少 1,且可用 ‘)‘ 加1.
str添加一个 ‘)‘,则 r 减少 1。

代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> res;
        dfs(res,"",n,0);
        return res;
    }
     
    void dfs(vector<string> &res, string str, int l, int r){
        if(l == 0 && r ==0){
            res.push_back(str);
            return;
        }
         
        if(l > 0) dfs(res, str+‘(‘, l - 1, r + 1);
        if(r > 0) dfs(res, str+‘)‘, l, r - 1);
    }
};





22. Generate Parentheses

标签:air   key   flow   str   public   附加   ase   out   uri   

原文地址:http://www.cnblogs.com/zhxshseu/p/a44db0600fe2adbb31aa501a69be6cec.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!