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 Solution {
public boolean isValid(String s) {
boolean result = false;
if (s == null || s.length() < 2) {
return false;
}
Stack<Character> st = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '('||s.charAt(i) == ')') {
if (st.isEmpty()) {
st.push(s.charAt(i));
} else {

if ((char) st.peek() + s.charAt(i) == 81
) {
st.pop();
} else {
st.push(s.charAt(i));
}
}

}
}
if (st.isEmpty()) {
result = true;
} else {
result = false;
}

return result;
}

public List<String> generateParenthesis(int n) {
List<String> result = generateParentheMax(n*2,n);
return result;
}

public List<String> generateParentheMax(int n,int num) {
if (n < 1) {
return new ArrayList<String>();
}
List<String> ls = null;
List<String> result = new ArrayList<String>();
if (n > 1) {
ls = generateParentheMax(n-1,num);

for (String st : ls) {
if (isValid(st)) {
String s1 = st + "(";
result.add(s1);
} else {
String s = st + ")";
result.add(s);
if(findCharSumInString(st, '(')<num){
String s1 = st + "(";
result.add(s1);
}
}
}

} else {

String s2 ="(";
result.add(s2);

}
return result;
}

private int findCharSumInString(String s, char c) {
int sum = 0;
if (null == s || s.length() == 0) {
return sum;
}
for (int i = 0; i < s.length(); i++) {
if (c == s.charAt(i)) {
sum++;
}
}
return sum;
}
}


网上有人有个更优美而且更好理解的方法。
public class Solution {
public List<String> generateParenthesis(int n) {
ArrayList<String> result = new ArrayList<String>();
ArrayList<Integer> diff = new ArrayList<Integer>();

result.add("");
diff.add(0);

for (int i = 0; i < 2 * n; i++) {
ArrayList<String> temp1 = new ArrayList<String>();
ArrayList<Integer> temp2 = new ArrayList<Integer>();

for (int j = 0; j < result.size(); j++) {
String s = result.get(j);
int k = diff.get(j);

if (i < 2 * n - 1) {
temp1.add(s + "(");
temp2.add(k + 1);
}

if (k > 0 && i < 2 * n - 1 || k == 1 && i == 2 * n - 1) {
temp1.add(s + ")");
temp2.add(k - 1);
}
}

result = new ArrayList<String>(temp1);
diff = new ArrayList<Integer>(temp2);
}

return result;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值