【面试题 & 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;
    }
};
发布了340 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/iCode_girl/article/details/105678790
今日推荐