Leet Code 22 Generate Parentheses - 生成括号 - Java
2016-06-08 00:00
507 查看
摘要: Leet Code 22 Generate Parentheses - 生成括号 - Java
问题原始链接 https://leetcode.com/problems/generate-parentheses
给定n对括号,写一个方法生成所有格式正确的括号组合。
例如,给定 n = 3,结果集如下:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
括号组合有两部分组成,右边i个括号的全部组合,左边是n-i-1个括号组合再在外面加一对括号。
问题原始链接 https://leetcode.com/problems/generate-parentheses
给定n对括号,写一个方法生成所有格式正确的括号组合。
例如,给定 n = 3,结果集如下:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
括号组合有两部分组成,右边i个括号的全部组合,左边是n-i-1个括号组合再在外面加一对括号。
[code=language-java] private static final List[] CACHE = new List[] { new ArrayList(), Arrays.asList("()"), Arrays.asList("(())", "()()"), Arrays.asList("((()))", "(()())", "(())()", "()(())", "()()()") }; public static List<String> generateParenthesis(int n) { if (n <= 0) { return new ArrayList<String>(); } if (n > 0 && n <= 3) { return CACHE ; } List<String> result = new ArrayList<String>(); for (int i = 0; i < n; i++) { List<String> right = generateParenthesis(i); List<String> left = generateParenthesis(n - i - 1); if (right.isEmpty()) { for (String l : left) { result.add("(" + l + ")"); } } else { if (left.isEmpty()) { for (String r : right) { result.add("()" + r); } } else { for (String l : left) { for (String r : right) { result.add("(" + l + ")" + r); } } } } } return result; }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解