zoukankan      html  css  js  c++  java
  • 边工作边刷题:70天一遍leetcode: day 61-6

    Different Ways to Add Parentheses

    要点:这题是另一种递归方式:分治,进一步说是catalan number方式的分治。比较有意思的是和Remove Invalid Parentheses这题的对比,remove里是从左到右递归。首先这题肯定不能这样递归,因为没法同步计算结果。另外,这题的特点是分治的两边是isolate的,意思就是两边加了括号,而每一个做中心的情况都延伸到边界,所以彼此也是isolate的。remove是基于每个存在的括号的,这个没法作为中心点。其他要点:

    • 如何区分算符和数字?分割点只在算符,如果loop以后没有算符,那么substring是一个数,只有最深层会只返回这个数(类似于表达式可以用二叉树来表示,只有leaf是数)。所以是通过结果集来确定的
    • 注意recursion function返回的是所有可能组合的结果,所以是list
    class Solution(object):
        def diffWaysToCompute(self, input):
            """
            :type input: str
            :rtype: List[int]
            """
            def diffWays(input):
                res = []
                for i in xrange(len(input)):
                    if input[i] in '+-*/':
                        left = diffWays(input[:i])
                        right = diffWays(input[i+1:])
                        for l in left:
                            for r in right:
                                if input[i]=='+':
                                    res.append(l+r)
                                if input[i]=='-':
                                    res.append(l-r)
                                if input[i]=='*':
                                    res.append(l*r)
                                if input[i]=='/':
                                    res.append(l/r)
                if not res:
                    res.append(int(input))
                return res
            
            return diffWays(input)
    
    
  • 相关阅读:
    WCF添加服务失败。服务元数据可能无法访问。请确保服务正在运行并且正在公开元数据。
    【C#】 实现WinForm中只能启动一个实例
    centos7防火墙问题
    ftp搭建记录
    centos7常用命令
    RocketMQ部署
    mongedb主从
    redis 主从复制+读写分离+哨兵
    keepalive+nginx
    分布架构分析
  • 原文地址:https://www.cnblogs.com/absolute/p/5690339.html
Copyright © 2011-2022 走看看