您的位置:首页 > 其它

[LeetCode] 22. Generate Parentheses

2016-12-15 16:02 405 查看
题目链接: 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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: