22. 括号生成
22. Generate Parentheses
题目描述
给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
LeetCode22. Generate Parentheses中等回溯算法
Java 实现
import java.util.ArrayList; import java.util.List; class Solution { public List<String> generateParenthesis(int n) { List<String> list = new ArrayList<>(); backtrack(list, "", 0, 0, n); return list; } public void backtrack(List<String> list, String str, int open, int close, int max) { if (str.length() == max * 2) { list.add(str); return; } if (open < max) { backtrack(list, str + "(", open + 1, close, max); } if (close < open) { backtrack(list, str + ")", open, close + 1, max); } } }
相似题目
参考资料
- https://leetcode.com/problems/generate-parentheses/discuss/10100/Easy-to-understand-Java-backtracking-solution
- https://leetcode-cn.com/problems/generate-parentheses/
- https://leetcode.com/problems/generate-parentheses/
来源:https://www.cnblogs.com/hglibin/p/10925869.html