[LeetCode] 22. Generate Parentheses

来源:互联网 发布:mac屏幕竖条一回消失 编辑:程序博客网 时间:2024/05/16 05:27

题目链接: https://leetcode.com/problems/generate-parentheses/

Description

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:

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

解题思路

递归回溯。需要添加一个辅助函数用来查找所有可能,在辅助函数中,每次都只有两种可能

  • 加左括号 (
  • 加右括号 )

因为要满足括号匹配,所以要加一个判断。可以加右括号的必要条件是当前需要的右括号 ) 的个数大于左括号 ( 的个数。

可以用反证法证明一下。
假如不满足这个条件,则右括号 ) 的个数小于等于左括号 ( 的个数,那么在此之前的括号中,必定存在至少一个右括号 ) 没有对应的左括号 (,出现类似())或者)(的结果,不满足题意。
所以,在进行下一轮的递归前,要判断左右括号个数的多少。

Code

class Solution {public:    void base(vector<string>& ans, int l, int r, string now) {        if (l == 0 && r == 0) {            ans.push_back(now);            return;        }        if (l > 0) base(ans, l - 1, r, now + "(");        if (r > l) base(ans, l, r - 1, now + ")");    }    vector<string> generateParenthesis(int n) {        vector<string> ans;        base(ans, n, n, "");        return ans;    }};
0 0