Leetcode Different Ways to ADD parentheses

Source: Internet
Author: User

Title Description:

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


Example 1

Input: "2-1-1" .

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

Output:[0, 2]


Example 2

Input:"2*3-4*5"

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

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

Presumably, given an expression, the results of the calculations produced by the different calculation order are output by means of parentheses. In the tip below the topic shows the use of divide-and-conquer method to solve problems.

Thinking: Split the input expression into left and right expressions based on the operator. The values of the left and right expressions are computed separately, and then the results are merged, such as 2*3-4*5, first divided by the first * number, the value of the left expression is 2, the right expression is 3-4*5, recursively calculates all the values of the expression on the left, for ( -17,-5) and multiply with the other, get (-34,-10), Then split with the second operator

Algorithm disadvantage: In the recursive process, there will be a large number of repeated calculations. As in the above example, the right-hand expression 4*5 is calculated when the first time is divided by a * when calculating the number. Additional space can be used to record and no longer study.

The code is as follows:

1 classsolution (object):2     defDiffwaystocompute (self, input):3         """4 : Type Input:str5 : Rtype:list[int]6         """7res = []8L =len (Input)9          forIinchRange (0, L):Ten             ifInput[i] = ='+' orInput[i] = ='-' orInput[i] = ='*': Oneleft =Self.diffwaystocompute (input[:i]) #左边表达式 Aright = Self.diffwaystocompute (input[i+1:]) #右边表达式 -                  forJinchLeft : -                      forKinchRight : the                         ifInput[i] = ='+': -Res.append (j +k) -                         elifInput[i] = ='-': -Res.append (J-k) +                         Else: -Res.append (J *k) +         ifres = =[]: #递归结束 A res.append (int (input)) at         returnRes

Another similar topic is:

Unique Binary Search Trees II

Title Description:

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

That is, given an n, write out the possible two-fork lookup tree from 1 to N. The previous calculation shows the number of two-fork trees from 1 to n. See http://www.cnblogs.com/missmzt/p/5525798.html

Problem-Solving ideas: 1. The same method of division and treatment, from 1 to n n number, the root node is: 1, 2, ... i.. N

2. When the root node value is I, then its left subtree is the value of the 1~i-1 right subtree value is: i+1 ~n

3. For the value of the left and right subtree, recursion in turn. Note that when the left or right subtree of node I is empty, set its subtree to none

If input 3 o'clock, need to write out 1, 2, 3 of the two fork find tree, when 1 is the root node, its left subtree is empty, the right subtree value is: Two or two, we use start and end to represent each recursive "root" node value range

The code is as follows:

1 classsolution (object):2     defgeneratetrees (self, n):3         """4 : Type N:int5 : Rtype:list[treenode]6         """7         returnSelf.gettree (1, N)8             9     defGettree (self, S, e):TenRET = [] One          forIinchRange (S, e+1): AL = Self.gettree (S, i-1) -R = Self.gettree (i+1, E) -              forXinch(lifLen (L)Else[None]): #左子树里面的每一颗子树分别作为其左子树, if 3 is the root node, 1, and 2, respectively the                  forYinch(rifLen (R)Else[None]): -Head =TreeNode (i) -Head.left =x -Head.right =y + Ret.append (head) -         returnRet

Leetcode Different Ways to ADD parentheses

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.