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

LeetCode 22. Generate Parentheses

时间:2016-05-29 00:39:52      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:

Problem:

https://leetcode.com/problems/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:

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

 

Thought:

use backtracking

reference: https://leetcode.com/discuss/104547/c-backtrack-solution-easy

Code C++:

class Solution {
public:
    void helper(vector<string>& solve, int m, int n, string s){
        if (m == 0 && n == 0) {
            solve.push_back(s);
            return;
        }
        
        if (m > 0)
            helper(solve, m - 1, n, s + ();
        if (m < n)
            helper(solve, m, n - 1, s + ));
    }
    vector<string> generateParenthesis(int n) {
        vector<string> solution;
        string s = "";
        helper(solution, n, n, s);
        return solution;
    }
};

 

LeetCode 22. Generate Parentheses

标签:

原文地址:http://www.cnblogs.com/gavinxing/p/5538618.html

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