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:
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
分析:
看见生成所有,基本可以确定是回溯问题,即DFS。
这个解法的特别之处在于,每次DFS时都会生成一个新的item实例,所以不需要递归结束时恢复现场。
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<String>();
dfs(res, new String(), n, n);
return res;
}
public void dfs(List<String> res, String item, int leftNum, int rightNum){
//如果剩余的左括号数大于右括号数,是非法的
if(leftNum > rightNum) return;
//递归终止
if(leftNum==0 && rightNum==0){
res.add(item);
return;
}
if(leftNum > 0)
//因为item+"("每次生成一个新的实例,所以不需要恢复现场
dfs(res, item+"(", leftNum-1, rightNum);
if(rightNum > 0)
dfs(res, item+")", leftNum, rightNum-1);
}
}