我的LeetCode代码仓:https://github.com/617076674/LeetCode
原题链接:https://leetcode-cn.com/problems/remove-invalid-parentheses/
题目描述:
知识点:回溯
思路一:回溯法(用栈来判断括号是否匹配)
由于没有任何剪枝操作,该回溯过程穷举了所有可能的情形,时间复杂度是O(2 ^ n),其中n为括号个数。空间复杂度是O(m),其中m为字符串的长度。
JAVA代码:
public class Solution {
private Set<String> set;
private String input;
private int maxLen = 0;
public List<String> removeInvalidParentheses(String s) {
set = new HashSet<>();
input = s;
removeInvalidParentheses(0, "", new LinkedList<>());
return new ArrayList<>(set);
}
private void removeInvalidParentheses(int index, String valid, LinkedList<Character> linkedList) {
if (index == input.length()) {
if (linkedList.isEmpty()) {
if (maxLen < valid.length()) {
maxLen = valid.length();
set.clear();
set.add(valid);
} else if (maxLen == valid.length()) {
set.add(valid);
}
}
retur