0%

leetCode-241:Different Ways to Add Parentheses

问题描述

给定一个表达式字符串,只包含数字和 +-* 符号,要求找出所有为表达式增加括号后的计算结果。题目链接:**点我**

样例输入输出

输入:”2-1-1”

输出:[0,2]

解释:

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

输入:”2*3-4*5”

输出:[-34,-14,-10,-10,10]

解释:

(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

问题解法

直接根据题目要求,使用递归方式找出所有为表达式添加括号的式子,计算其结果,进行汇总。为了减少重复计算,可以使用一个 map 将计算过的表达式的值存起来,方便下次直接取用。代码如下

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
class Solution
{
public List<Integer> diffWaysToCompute(String expression)
{
Map<String, List<Integer>> map = new HashMap<>();
return diffWaysToCompute(expression, map);
}

private List<Integer> diffWaysToCompute(String expression, Map<String, List<Integer>> map)
{
if (map.containsKey(expression))
{
return map.get(expression);
}

List<Integer> result = new ArrayList<>();
if (getNextOpIndex(expression, 0) == -1)
{
result.add(Integer.parseInt(expression));
map.put(expression, result);
return result;
}

int len = expression.length();
for (int i = 0; i < len; )
{
int index = getNextOpIndex(expression, i);
if (index == -1)
{
break;
}

List<Integer> left = diffWaysToCompute(expression.substring(0, index), map);
List<Integer> right = diffWaysToCompute(expression.substring(index + 1), map);
result.addAll(calc(left, right, expression.charAt(index)));

i = index + 1;
}

map.put(expression, result);
return result;
}

private int getNextOpIndex(String expression, int start)
{
for (int i = start; i < expression.length(); i++)
{
if (!Character.isDigit(expression.charAt(i)))
{
return i;
}
}

return -1;
}

private List<Integer> calc(List<Integer> left, List<Integer> right, char op)
{
List<Integer> result = new ArrayList<>();
for (Integer leftValue : left)
{
for (Integer rightValue : right)
{
int value;
if (op == '+')
{
value = leftValue + rightValue;
}
else if (op == '-')
{
value = leftValue - rightValue;
}
else
{
value = leftValue * rightValue;
}

result.add(value);
}
}

return result;
}
}