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

[LeetCode] 22 - Generate Parentheses

时间:2015-08-29 16:37:44      阅读:116      评论: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:

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

 

class Solution {
public:
  void doGenerate(int x0, int x1, string&& s) {
    if (!x0 && !x1) {
      m_result.emplace_back(s);
    }
    if (x0 > 0) {
      doGenerate(x0 -1, x1, s + "(");
    }
    if (x1 > 0 && x1 > x0) {
      doGenerate(x0, x1 - 1 , s + ")");
    }
  }

  vector<string> generateParenthesis(int n) {
    int x0 = n, x1 = n;
    m_result.clear();
    doGenerate(n, n, "");
    return m_result;
  }
private:
  vector<string> m_result;
};

[LeetCode] 22 - Generate Parentheses

标签:

原文地址:http://www.cnblogs.com/shoemaker/p/4769202.html

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