Generate Parentheses 生成有意义的括号对
2014-10-23 22:04
441 查看
Question:
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:
思想:
1. 采用递归,解决此题。
2. 递归条件:剩下的'('的数要<=')'的数量,且两者的剩余数量都要大于等0,这样才能保证‘()’的匹配。
代码:
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:
"((()))", "(()())", "(())()", "()(())", "()()()"。
思想:
1. 采用递归,解决此题。
2. 递归条件:剩下的'('的数要<=')'的数量,且两者的剩余数量都要大于等0,这样才能保证‘()’的匹配。
代码:
public class Solution { public List<String> generateParenthesis(int n) { List<String> myResult = new ArrayList<String>(); String transfer = ""; process(n, n, (ArrayList<String>)myResult, transfer); return myResult; } public static void process(int left, int right, ArrayList<String> myResult, String transfer){ if(left == 0 && right == 0) myResult.add(transfer); // add to myResult if(left <= right && left>0) process(left-1, right, myResult,(transfer + '(') ); // make sure left>=0 if(left < right && left>=0 ) process(left, right-1, myResult, (transfer + ')') ); // right-1>=left } }
相关文章推荐
- Leet Code 22 Generate Parentheses - 生成括号 - Java
- [Lintcode]Generate Parentheses 生成括号
- Generate Parentheses--生成匹配括号(重)
- [Leetcode] generate parentheses 生成括号
- LeetCode 22 Generate Parentheses(生成括号)
- 代码的优化过程: 生成括号 Generate Parentheses
- LeetCode | Generate Parentheses(生成括号)
- Generate Parentheses:生成括号对
- 【LeetCode-面试算法经典-Java实现】【022-Generate Parentheses(生成括号)】
- [LeetCode] Generate Parentheses 生成括号
- [LintCode] Generate Parentheses 生成括号
- LeetCode22 Generate Parentheses 括号生成
- Generate Parentheses 生成括号-- LintCode题解
- Generate parentheses,生成括号对,递归,深度优先搜索。
- LeetCode 22 Generate Parentheses(生成括号)
- Leetcode #22 Generate Parentheses 创建括号 解题报告
- LeetCode22——Generate Parentheses(给定n对括号,然后看有多少正确的括号组合)
- Generate Parentheses (括号匹配)【leetcode】
- LeetCode OJ 之 Generate Parentheses (产生括号)
- [leetcode 22]Generate Parentheses-----n对括号可以组成的括号对序列