代码拉取完成,页面将自动刷新
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.List;
/**
* 22. Generate Parentheses
*
* 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 _22 {
public static class Solution1 {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList();
backtrack(result, "", 0, 0, n);
return result;
}
void backtrack(List<String> result, String str, int left, int right, int max) {
if (str.length() == max * 2) {
result.add(str);
return;
}
if (left < max) {
backtrack(result, str + "(", left + 1, right, max);
}
if (right < left) {
backtrack(result, str + ")", left, right + 1, max);
}
}
}
public static class Solution2 {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList();
if (n == 0) {
return result;
}
helper(result, "", n, n);
return result;
}
void helper(List<String> result, String par, int left, int right) {
if (left > 0) {
helper(result, par + "(", left - 1, right);
}
if (right > left) {
helper(result, par + ")", left, right - 1);
}
if (right == 0) {
result.add(par);
}
}
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。