【面試題 & LeetCode 22】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:

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

思路

遞歸

代碼

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> res;
        dfs(n, 0, 0, "", res);
        return res;
    }
    
    void dfs(int n, int l, int r, string cur, vector<string>& res) {
        if (r > l) return;
        if (r == n) {
            res.push_back(cur);
            return;
        }
        if (l < n) dfs(n, l+1, r, cur+'(', res);
        if (r < n) dfs(n, l, r+1, cur+')', res);
        return;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章