zoukankan      html  css  js  c++  java
  • 算法8-----Different Ways to Add Parentheses(不同括号结果)

    题目:

    Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +, - and *.


    Example 1

    Input: "2-1-1".

    ((2-1)-1) = 0
    (2-(1-1)) = 2

    Output: [0, 2]


    Example 2

    Input: "2*3-4*5"

    (2*(3-(4*5))) = -34
    ((2*3)-(4*5)) = -14
    ((2*(3-4))*5) = -10
    (2*((3-4)*5)) = -10
    (((2*3)-4)*5) = 10

    Output: [-34, -14, -10, -10, 10]

     

    解法:分治法

    思路:

    分:遍历每个符号,分为符号前和后。如:"2-1-1-1",第1个‘-’分为 ‘2’ 和 ‘1-1-1’ ;第二个 '-' 分为 ‘2-1’ 和 ‘1-1’,第三个‘-’ 分为‘2-1-1’和‘1’

    治:最后为一个数,则返回该数。

    并:

      对于每一次的分,如【2-1*3】  -   【1-1*4】  ,a=‘2-1*3’ 和 b=‘1-1*4’, a,b都递归计算所有的可能结果存入一个数组中,遍历相加减乘。a有2种结果【3,-1】,b有两种结果【0,-3】,如果a和b之间是 ‘-’,则 a-b 就会返回4种结果。

    代码如下:

        def diffWaysToCompute(input):
            """
            :type input: str
            :rtype: List[int]
            """
            res=[]
            result=0
            for i,c in enumerate(input):
                if c in "+-*":
                    for a in diffWaysToCompute(input[:i]):
                        for b in diffWaysToCompute(input[i+1:]):
                            if c=='+':
                                res.append(a+b)
                            elif c=='-':
                                res.append(a-b)
                            else:
                                res.append(a*b)
            
            return res or [int(input)]
  • 相关阅读:
    Sharp Develop发布了1.0.3版本
    【历代Windows操作系统大观】(转)
    Matlab与vc混合编程中的问题,使用idl文件
    明天回湖北!今天要开始收拾烂摊子了
    MongoDB深究之ObjectId
    MVC设计模式
    ASP.NET验证控件详解
    C# 中的 LINQ 入门学习摘记
    15款在线科学计算器
    从底层了解ASP.NET架构
  • 原文地址:https://www.cnblogs.com/Lee-yl/p/8928063.html
Copyright © 2011-2022 走看看