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

1
2
3
4
5
Input: "2-1-1".
((2-1)-1) = 0
(2-(1-1)) = 2
Output: [0, 2]

Example 2

1
2
3
4
5
6
7
8
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:

用Divide & Conquer的思想,按照每一个运算符号分成左右两边。每边计算一下结果然后按照运算符号结合起来。当只有数字的时候所生成的res一定为空,这个时候就把数字加入res即可。

lang: java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
public List<Integer> diffWaysToCompute(String input) {
List<Integer> res = new ArrayList<>();
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == '+' || input.charAt(i) == '-' || input.charAt(i) == '*') {
String left = input.substring(0, i);
String right = input.substring(i + 1);
List<Integer> leftRes = diffWaysToCompute(left);
List<Integer> rightRes = diffWaysToCompute(right);
for (int l : leftRes) {
for (int r : rightRes) {
switch (input.charAt(i)) {
case '+' :
res.add(l + r);
break;
case '-':
res.add(l - r);
break;
case '*':
res.add( l * r);
break;
}
}
}
}
}
if (res.size() == 0) {
res.add(Integer.parseInt(input));
}
return res;
}
}