leetcode 0022
说明
只是为了记录一下,不求多快,也不深究。
会简要描述思路,代码中不写注释。
如碰到不会做的用了别人代码会在博客中标出。
题目描述
思路
isMatch函数用来判断括号是否匹配;
用递归生成所有可能情况的排列组合;
判断是否Match即可。
class Solution {
public boolean isMatch(String s) {
LinkedList<Character> stack = new LinkedList<Character>();
stack.add(s.charAt(0));
for(int i = 1;i<s.length();++i) {
if(stack.size() == 0) {
stack.add(s.charAt(i));
}else {
char ch = stack.pollLast();
if(s.charAt(i) == ')'&&ch == '(') {
continue;
}else if(s.charAt(i) == '('&&ch == '(') {
stack.add('(');
stack.add('(');
}else {
return false;
}
}
}
if(stack.size() == 0) {
return true;
}else {
return false;
}
}
public List<String> generateParenthesis(int n) {
List<String> str = new ArrayList<String>();
if(n<1) {
return str;
}
getAllStr("", 0, 2*n, str);
return str;
}
public void getAllStr(String curr,int currIdx,int n,List<String> str) {
if(currIdx == n) {
if(isMatch(curr)) {
str.add(curr);
}
}else {
getAllStr(curr+'(', currIdx+1, n, str);
getAllStr(curr+')', currIdx+1, n, str);
}
}
}