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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
这是我的代码
public static List<String> generateParenthesis(int n) {
Set<String> set = new HashSet<String>();
StringBuilder sb = new StringBuilder();
while(n -- > 0) {
sb.append("()");
}
String s = sb.toString();
generateParenthesis(set, s.toCharArray(), s.length() - 1, false);
return new ArrayList<String>(set);
}
private static void generateParenthesis(Set<String> set, char[] s, int end, boolean isSkip) {
String ns = new String(s);
if(!set.contains(ns) || isSkip) {
set.add(ns);
int index = 0;
if((index = ns.lastIndexOf(")(")) != -1 && end < index + 2) {
generateParenthesis(set, s, index + 2, true);
}
for(int i = end; i >= 1; i--) {
if(s[i] =='(' && s[i - 1] ==')') {
s[i] = ')'; s[i-1] = '(';
generateParenthesis(set, s, i - 1, false);
s[i] = '('; s[i-1] = ')';
}
}
}
}
别人的代码
public List<String> generateParenthesis(int n) {
List<String> list = new ArrayList<String>();
backtrack(list, "", 0, 0, n);
return list;
}
public 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);
}
这个算法很有意思,别人的解法相当的不错,他是从创建的角度来思考的。这让我想起一句话:如果以出生的那一刻定义为拥有全部时间,那么每一刻我的时间都在流逝;如果以死亡的那一刻定义为拥有全部时间,那么每一刻我都在收获时间。