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)]
  • 相关阅读:
    程序员需要看的书
    linux常见命令实践.
    数据库使用简单总结
    剑指offer【书】之简历抒写
    面试中自己项目和你应该问的问题环节总结
    Matlab近期用到的函数(持续更新)
    排序-快速排序算法
    系统运维-hub, repeater, switch, router初览
    C++基础-位运算
    排序-冒泡排序
  • 原文地址:https://www.cnblogs.com/Lee-yl/p/8928063.html
Copyright © 2011-2022 走看看