zoukankan      html  css  js  c++  java
  • leetcode 之 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*3-4*5 ,首先以第一个*号分割,左边表达式的值为2,右边表达式为3-4*5, 递归计算出右边表达式的所有值,为(-17,-5) 并与左边做乘法,得到(-34, -10),然后以第二个运算符分割

    算法缺点: 在递归过程中,会出现大量的重复计算。如上例, 在计算- 号时,右边表达式4*5在第一次以*分割时,以经计算过了。这里可以采用额外的空间进行记录,不再研究。

    代码如下:

     1 class Solution(object):
     2     def diffWaysToCompute(self, input):
     3         """
     4         :type input: str
     5         :rtype: List[int]
     6         """
     7         res = []
     8         l = len(input)
     9         for i in range(0, l):
    10             if input[i] == '+' or input[i] == '-' or input[i] == '*':
    11                 left = self.diffWaysToCompute(input[:i])  #左边表达式
    12                 right = self.diffWaysToCompute(input[i+1:]) #右边表达式
    13                 for j in left:
    14                     for k in right:
    15                         if input[i] == '+':
    16                             res.append(j + k)
    17                         elif input[i] == '-':
    18                             res.append(j - k)
    19                         else:
    20                             res.append(j * k)
    21         if res == []:  #递归结束
    22             res.append(int(input))
    23         return res

    另一道相似的题目为:

    Unique Binary Search Trees II

    题目描述:

    Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.

    For example,
    Given n = 3, your program should return all 5 unique BST's shown below.

       1         3     3      2      1
               /     /      /       
         3     2     1      1   3      2
        /     /                        
       2     1         2                 3
    

     即给定一个n,写出从1到n所有的可能的二叉查找树。之前 的计算出从1到n的二叉树的个数。见http://www.cnblogs.com/missmzt/p/5525798.html

    解题思路: 1.同样采用分治法,从1到n n个数,根节点依次为: 1, 2,... i..n

         2. 当根节点取值为i时,  这时其左子树的取值为1~i-1 右子树的取值为: i+1 ~n

         3. 针对左右子树的取值,依次递归。 注意当节点i的左子树或右子树为空时,设置其子树为none

    如 输入3 时, 需要写出 1, 2, 3 的二叉查找树, 当1 为根节点时, 其 左子树为空,右子树取值为: 2~3, 我们使用start 和end 来表示每次递归”根“节点的取值范围

    代码如下:

     1 class Solution(object):
     2     def generateTrees(self, n):
     3         """
     4         :type n: int
     5         :rtype: List[TreeNode]
     6         """
     7         return self.getTree(1, n)
     8             
     9     def getTree(self, s, e):
    10         ret = []
    11         for i in range (s, e+1):
    12             l = self.getTree(s, i-1)
    13             r = self.getTree(i+1, e)
    14             for x in (l if len(l) else [None]):  #左子树里面的每一颗子树分别作为其左子树, 如3为根节点时,分别为1, 和 2
    15                 for y in (r if len(r) else [None]):
    16                     head = TreeNode(i)
    17                     head.left = x
    18                     head.right = y
    19                     ret.append(head)
    20         return ret
    ~~~~~
  • 相关阅读:
    开发细节
    html
    java学习
    Promise对象
    强制转换和隐式转换
    借助防抖解决输入框的非空校验
    setTimeout
    Symbol类型
    js API
    vue 使用mixin
  • 原文地址:https://www.cnblogs.com/missmzt/p/5552011.html
Copyright © 2011-2022 走看看