LeetCode算法入门- Generate Parentheses -day16
- 题目描述
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:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
-
题目分析:给定一个数字n,列出所有合法的序列,条件是左括号个数要大于或等于右括号个数:使用递归来实现
-
Java实现:
class Solution {public List<String> generateParenthesis(int n) {List<String> result = new ArrayList<>();helper(n,n,"",result);return result;}public static void helper(int left, int right, String tmp, List<String> result){if(left == 0 && right == 0){result.add(tmp);return ;}if(left < 0 || right < 0 || left > right){return ;}helper(left-1, right, tmp+"(",result);helper(left, right-1, tmp+")",result);}
}