这篇文章是程序自动发表的,详情可以见
这里
href="http://ounix1xcw.bkt.clouddn.com/github.markdown.css" rel="stylesheet">
href="http://ounix1xcw.bkt.clouddn.com/github.markdown.css" rel="stylesheet">
这是leetcode的第301题--Remove Invalid Parentheses
题目 Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.
Note: The input string may contain letters other than the parentheses ( and ).
Examples: "()())()" -> ["()()()", "(())()"] "(a)())()" -> ["(a)()()", "(a())()"] ")(" -> [""]
思路 代码是别人的,我写得太矬。我写了几十行代码,人家只用了几行:sob:。这道题可以用BFSFS,注意到对于一个坏括号列,要变成好括号列,要删去的括号种类(即(
或者)
)和数目是固定的,所以可以逐个搜索删去1,2,3...个后,是否有好括号列。不过这样不足的一点就是太慢了,搜索得太多了。
show me the code
class Solution(object): def judgePoint24(self, nums): """ :type nums: List[int] :rtype: bool """ return self.exam(nums,4) def div(a,b): if abs(b)< 0.01: return 10000 return a/float(b) from operator import mul,add,sub ops = [mul,add,sub,div] def exam(self,nums,n): if n is 1 : if abs(nums[0] -24)<0.01: return True else:return False for op in self.ops: for i in range(n-1): for j in range(i 1,n): rst1 = op(nums[i],nums[j]) rst2 = op(nums[j],nums[i]) tmp = nums[:] tmp.remove(nums[i]) tmp.remove(nums[j]) tmp.append(rst1) if self.exam(tmp,n-1): return True if rst1 != rst2: tmp[-1] = rst2 if self.exam(tmp,n-1): return True return False