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;
    }
};

 

posted on 2016-05-28 23:15  gavinXing  阅读(102)  评论(0编辑  收藏  举报