题目:
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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
大意:
给定n对括号,输出他们所有正确的组合。
思路:
采用深度优先的递归方法。
代码:
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>();
String s = "";
dfs(result, s, n, n);
return result;
}
private void dfs(List<String> result, String s, int left, int right) {
if(left > right) {
return;
}
if(left == 0 && right == 0) {
result.add(s);
return;
}
if(left > 0) {
dfs(result, s + "(", left - 1, right);
}
if(right > 0) {
dfs(result, s + ")", left, right - 1);
}
}
}
注意点:
传递String类型的变量是值传递。
递归调用中使用全局变量和函数参数之间的差异:
对树、图进行遍历时,包括 前序、中序、后序、深度搜索、广度搜索
存在一些参数,可以用
1. 全局变量表示,递归结束后必须对该变量修改,恢复原值
2. 普通函数参数,因为递归调用函数时,实际上,从内存分布上看,每一层调用都保存了该层函数的参数,因此递归返回上层时,不会影响原参数值