标签:
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
使用回溯法。
设已放置左括号数量为LC,右括号数量为RC,输入整数位n.
放置左括号的条件为LC<n, 放置右括号的条件为LC > RC && RC<n.
0. 优先放置左括号,左括号放置完了再放置右括号。右括号放置完成后得到一个可行解。之后进行回溯,回溯的方法是:
1. 遇到右括号,删除右括号,RC = RC - 1;
2. 遇到左括号,删除左括号,LC = LC - 1;
如果符合放置右括号的条件,则放置右括号,RC = RC + 1;回到第0步;
如果不符合放置右括号的条件,回到第1步;
下面分别给出非递归和递归的代码。
1. 非递归代码
public List<String> generateParenthesis(int n) { int lc = 1; int rc = 0; List<String> results = new ArrayList<String>(); String solution = "("; while(solution.charAt(0) == ‘(‘) { for(int i=lc+rc; i<2*n; i++) { if(lc < n) { solution += "("; lc++; } else { solution += ")"; rc++; } } results.add(solution); int i = solution.length()-1; for(; i>=0; i--) { if(solution.charAt(i) == ‘)‘) { rc--; } else { lc--; if(lc > rc && rc < n) { solution = solution.substring(0, i) + ")"; rc++; break; } } } if(i == -1) break; } return results; }
2. 递归代码
List<String> results = new ArrayList<String>(); public void generateParenthesisHelp(int lc, int rc, int n, String solution)
if(lc < n) { generateParenthesisHelp(lc+1, rc, n, solution+"(");
if(lc > rc && rc < n) { generateParenthesisHelp(lc, rc+1, n, solution+")"); } } else if(rc < n) { generateParenthesisHelp(lc, rc+1, n, solution+")"); } else {
results.add(solution); } }
LeetCode-22 Generate Parentheses
标签:
原文地址:http://www.cnblogs.com/linxiong/p/4291155.html