老卫带你学---leetcode刷题(301. 删除无效的括号)

301. 删除无效的括号

问题:

给你一个由若干括号和字母组成的字符串 s ,删除最小数量的无效括号,使得输入的字符串有效。

返回所有可能的结果。答案可以按 任意顺序 返回。

示例 1:

输入:s = "()())()"
输出:["(())()","()()()"]
示例 2
输入:s = "(a)())()"
输出:["(a())()","(a)()()"]
示例 3
输入:s = ")("
输出:[""]

提示:

1 <= s.length <= 25
s 由小写英文字母以及括号 '('')' 组成
s 中至多含 20 个括号

解决

这道题其实可以用DFS,也可以用BFS,我个人觉得BFS会更加清晰一些。

核心思想在于,通过BFS,逐层向下去寻找有效的括号集合。

初始状态就是一个Set(s),然后下一层就是删掉一个元素的不同字符串组合。因为题目说了,删除最小数量,那么如果校验发现这一层又valid成功的,就可以直接输出,不用再往下寻找了。

// The function checks if a given string has valid balanced parentheses.
func isValid(s string) bool{
	vcount := 0
	for _,i := range s{
		if i=='('{
			vcount++
		}
		if i == ')'{
			vcount--
		}
		if vcount<0{
			return false
		}
	}
	if vcount!=0{
		return false
	} else {
		return true
	}
}

// The filter function takes a list of strings and a function as input, and returns a new list
// containing only the strings for which the function returns true.
func filter(l []string, fn func(string) bool) []string{
	var r []string
	for _,i:= range l{
		if fn(i){
			r = append(r, i)
		}
	}
	return r
}

// The function takes a map of strings to booleans and returns a list of the keys from the map.
func MapToList(m map[string]bool) []string{
	var r []string
	for k,_ := range(m){
		r= append(r, k)
	}
	return r
}


// 
func removeInvalidParentheses(s string) []string {
	level := make(map[string]bool,len(s))
	level[s] = true
	for{
		valid := filter(MapToList(level), isValid)
		if len(valid)>0{
			return valid
		}
		next_level := make(map[string]bool)
		for _,i:= range MapToList(level){
			for j,_ := range i{
				if i[j] =='(' || i[j]==')'{
					next_level[i[:j]+i[j+1:]] = true
				}
			}
		}
		level = next_level
	}
}

你可能感兴趣的:(leetcode,算法)