xinyu04

导航

LeetCode 22 Generate Parentheses DFS

Given \(n\) pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]

Solution

考虑 \(DFS\) 来递归: 用 \(numR\) 表示右括号数目,起始为 \(n\)\(numL\) 表示左括号可用的数目。当 \(numR=numL=0\) 表示全部用完,此时将字符串加入答案。

点击查看代码
class Solution {
private:
    vector<string> ans;
    
    void dfs(vector<string>& ans, int numL, int numR, string cur){
        if(numL==0 && numR==0){
            ans.push_back(cur); return;
        }
        if(numR>0)dfs(ans, numL, numR-1, cur+")");
        if(numL>0)dfs(ans, numL-1, numR+1, cur+"(");
    }
    
public:
    vector<string> generateParenthesis(int n) {
        dfs(ans, n, 0, "");
        return ans;
    }
};

posted on 2022-07-27 17:03  Blackzxy  阅读(12)  评论(0编辑  收藏  举报