String-22-Generate Parentheses
2018-02-09 15:19
309 查看
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:
Solution:
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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
Solution:
class Solution { public List<String> generateParenthesis(int n) { List<String> combinations = new ArrayList(); generateAll(new char[2 * n], 0, combinations); return combinations; } public void generateAll(char[] current, int pos, List<String> result) { if (pos == current.length) { if (valid(current)) result.add(new String(current)); } else { current[pos] = '('; generateAll(current, pos+1, result); current[pos] = ')'; generateAll(current, pos+1, result); } } public boolean valid(char[] current) { int balance = 0; for (char c: current) { if (c == '(') balance++; else balance--; if (balance < 0) return false; } return (balance == 0); } }
相关文章推荐
- 22.Generate Parentheses (String; dfs)
- LeetCode 22 Generate Parentheses (C,C++,Java,Python)
- Leetcode 22 Generate Parentheses
- 【LeetCode】【Array】【22】Generate Parentheses
- 22 Generate Parentheses
- [leetcode 22]Generate Parentheses-----n对括号可以组成的括号对序列
- d22. Generate Parentheses ( 以后不要钻牛角尖)
- Leetcode Generate Parentheses 22
- LeetCode 22 Generate Parentheses
- 【22】Generate Parentheses
- 22. Generate Parentheses
- LeetCode_22 Generate Parentheses
- Leetcode 22 Generate Parentheses
- LeetCode 22_Generate Parentheses
- [Leetcode] 22- Generate Parentheses
- Leetcode 22 Generate Parentheses 搜索与DP的纠结
- 22. Generate Parentheses
- leetcode-22-Generate Parentheses
- LeetCode 22 Generate Parentheses 卡特兰数问题,有待进一步学习
- LeetCode 22 Generate Parentheses(生成括号)