谨慎后,1A的概率貌似高了些
算是20题的升级版吧,
利用递归来拼成string,然后通过20. 有效的括号该题的代码来判断生成的string合不合法
看代码吧
class Solution {
public List<String> generateParenthesis(int n) {
List<String> ans = new ArrayList<>();
dfs(ans, "", n, n);
return ans;
}
public void dfs(List<String> list, String st, int left, int right) {
if (left == 0 && right == 0 && isValid(st)) {
list.add(st);
}
if (left > 0) dfs(list, st + "(", left-1, right);
if (right > 0) dfs(list, st + ")", left, right-1);
}
public boolean isValid(String s) {
Stack<Character> characterStack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
switch (s.charAt(i)) {
case ‘(‘:
case ‘[‘:
case ‘{‘:
characterStack.push(s.charAt(i));
break;
case ‘)‘:
if (!characterStack.isEmpty() && characterStack.peek() == ‘(‘) {
characterStack.pop();
break;
} else {
return false;
}
case ‘]‘:
if (!characterStack.isEmpty() && characterStack.peek() == ‘[‘) {
characterStack.pop();
break;
} else {
return false;
}
case ‘}‘:
if (!characterStack.isEmpty() && characterStack.peek() == ‘{‘) {
characterStack.pop();
break;
} else {
return false;
}
}
}
return characterStack.isEmpty();
}
}
AC后观摩榜单大神的代码,发现其实不必使用isValid()函数判断合法性,
只需保证已经生成的字符串中,左括号的数量>=右括号的数量即可,反过来讲剩余待使用左括号数量要<剩余待使用的右括号数量,否则,当前分支剪掉,代码如下
class Solution {
public List<String> generateParenthesis(int n) {
List<String> ans = new ArrayList<>();
dfs(ans, "", n, n);
return ans;
}
public void dfs(List<String> list, String st, int left, int right) {
if (right < left) return;
if (left == 0 && right == 0) {
list.add(st);
}
if (left > 0) dfs(list, st + "(", left - 1, right);
if (right > 0) dfs(list, st + ")", left, right - 1);
}
}
尼玛优化后居然比优化前慢5ms,严重怀疑leetcode评测机有毛病,代码跑多久看RP
原文地址:https://www.cnblogs.com/acbingo/p/9251617.html
时间: 2024-10-08 19:25:38