[一起来刷leetcode吧][24]--No.301 Remove Invalid Parentheses

这篇文章是程序自动发表的,详情可以见 这里
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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值