1. 括号(0809)
设计一种算法,打印n对括号的所有合法的(例如,开闭一一对应)组合。
说明:解集不能包含重复的子集。
例如,给出 n = 3,生成结果为:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
class Solution {
List<String> list = new ArrayList<>();
char[] arr = new char[]{'(',')'};
public List<String> generateParenthesis(int n) {
StringBuilder sb = new StringBuilder();
backtrack(sb,n,0,0);
return list;
}
//countl表示左括号的数量,countr表示右括号的数量
public void backtrack(StringBuilder sb,int n,int countl,int countr){
if(countl < countr || countl > n){
return;
}
if(sb.length() == 2*n){
list.add(sb.toString());
}
for(char c : arr){
sb.append(c);
if(c == '('){
countl++;
backtrack(sb,n,countl,countr);
sb.deleteCharAt(sb.length()-1);
countl--;
}else{
countr++;
backtrack(sb,n,countl,countr);
sb.deleteCharAt(sb.length()-1);
countr--;
}
}
}
}
2. 有效的括号(20)
class Solution {
public boolean isValid(String s) {
int len = s.length();
if(len % 2 == 1) return false;
char[] arr = s.toCharArray();
Stack<Character> sin = new Stack<>();
Stack<Character> sou = new Stack<>();
for(char c : arr){
sin.push(c);
}
while(!sin.isEmpty()){
char tmp = sin.pop();
if(tmp == ']' || tmp == '}' ||tmp == ')')
sou.push(tmp);
else{
if(sou.isEmpty()) return false;
boolean b = isValidhelper(tmp,sou.pop());
if(!b) return false;
}
}
return true;
}
public boolean isValidhelper(char c1,char c2){
if(c1 == '(' && c2 == ')') return true;
if(c1 == '[' && c2 == ']') return true;
if(c1 == '{' && c2 == '}') return true;
return false;
}
}
3. 有效的括号(20)