链接:https://leetcode.com/problems/combination-sum/
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,求出所有有效的n组小括号组成的字符串。
思路
维护一个字符串str
,假设该字符串包含个m个(
,k个)
,这里m <= n
,k <= m
。当str
的长度等于2*n
时,该字符串就是有效的。否则当m < n
时,向str
中添加一个(
;当k <= m
时,向str
中添加一个)
;
代码
public static List<String> solution2(int n){
List<String> list = new ArrayList<>();
backtrack(list, "", 0, 0, n);
return list;
}
//open代表str中含有多少个'(',close代表str中含有多少个')',max代表最多有多少个‘(’
private static void backtrack(List<String> list, String str, int open, int close, int max){
if(str.length() == max * 2){
list.add(str);
return;
}
if(open < max)
backtrack(list, str + "(", open + 1, close, max);
if(close < open)
backtrack(list, str + ")", open, close + 1, max);
}
算法的思想比较接近深度优先算法。