您的位置:首页 > 其它

leetcode:Generate Parentheses

2014-10-06 10:30 267 查看
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 class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new LinkedList<>();
result.add("()");
for (int i = 1; i < n; ++i) {
Set<String> buffer = new HashSet<>();
for (int j = 0; j < result.size(); ++j) {
String str = result.get(j);
for (int k = 0; k < str.length(); ++k) {
buffer.add(str.substring(0, k) + "()" + str.substring(k, str.length()));
}
}
result.clear();
result.addAll(buffer);
}
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: