241. 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]

 

含义:计算出对于一串字符串所有加括号下结果的可能

 1     public List<Integer> diffWaysToCompute(String input) {
 2 //        分而治之。对于输入字符串,若其中有运算符,则将其分为两部分,分别递归计算其值,然后将左值集合与右值集合进行交叉运算,将运算结果放入结果集中;
 3 //        若没有运算符,则直接将字符串转化为整型数放入结果集中。
 4         List<Integer> result = new ArrayList<>();
 5         for (int i = 0; i < input.length(); i++) {
 6             Character ch = input.charAt(i);
 7             if (ch.equals('+') || ch.equals('-') || ch.equals('*')) {
 8                 List<Integer> leftResult = diffWaysToCompute(input.substring(0, i));
 9                 List<Integer> rightResult = diffWaysToCompute(input.substring(i + 1));
10                 for (Integer left : leftResult)
11                     for (Integer right : rightResult) {
12                         switch (ch) {
13                             case '+':
14                                 result.add(left + right);
15                                 break;
16                             case '-':
17                                 result.add(left - right);
18                                 break;
19                             case '*':
20                                 result.add(left * right);
21                                 break;
22                         }
23                     }
24             }
25         }
26         if (result.size() == 0) result.add(Integer.valueOf(input));
27         return result;    
28     }

 

posted @ 2017-10-25 18:55  daniel456  阅读(128)  评论(0编辑  收藏  举报