22.Generate Parentheses
给定一个整数n,包含 n个左括号和 n个右括号,将这n对括号组成有效的符号类型。
For example, given n = 3, a solution set is:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
思路来源,Grandyang:
利用递归,需要用到辅助函数,参数为 左括号left,右括号right,递归调用(left-1, right, string+'(', res)和 (left, right-1, string+')',res),当left=right=0表示组合正常,将其结果加入容器中,而 right > left 表示右括号用的比左括号多,如 ")" 这种非法情形,就return.
class Solution { public: vector<string> generateParenthrsis(int n) { if (n <= 0) return{}; vector<string> res; generateParenthrsisDFS(n, n, "", res); return res; } void generateParenthrsisDFS(int left, int right, string s, vector<string>& ans) { if (right < left) return; if (left == 0 && right == 0) ans.push_back(s); else { if (left > 0) generateParenthrsisDFS(left - 1, right, s + '(', ans); if (right > 0) generateParenthrsisDFS(left, right - 1, s + ')', ans); } } };
Java 版:
class Solution { public List<String> generateParenthesis(int n) { List<String> res = new ArrayList<>(); this.generateParenthesisDFS(n, n, "", res); return res; } public void generateParenthesisDFS(int left, int right, String s, List<String> res){ if(left == 0 && right == 0) res.add(s); else if(left > right || left < 0 || right < 0) return; else { this.generateParenthesisDFS(left - 1, right, s + "(", res); this.generateParenthesisDFS(left, right - 1, s + ")", res); } } }