1. 程式人生 > >【LeetCode】108.Generate Parentheses

【LeetCode】108.Generate Parentheses

題目描述(Medium)

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:

題目連結

https://leetcode.com/problems/combination-sum-ii/description/

Example 1:

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

演算法分析

當左括號出現次數<n時,就可以放置新的左括號;當右括號出現次數小於左括號出現次數時,就可以放置新的右括號。當l==n時,做右括號補全。

提交程式碼:

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        string solution;
        dfs(solution, n, 0, 0);
        return this->result;
    }

private:
    vector<string> result;
    void dfs(string &solution, int n, int l, int r) {
        if (l == n)
        {
            string s(solution);
            this->result.push_back(s.append(n - r, ')'));
            return;
        }
        
        solution.push_back('(');
        dfs(solution, n, l + 1, r);
        solution.pop_back();
        
        if (l > r) {
            solution.push_back(')');
            dfs(solution, n, l, r + 1);
            solution.pop_back(); 
        }
    }
};