[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”.

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

Output: [0, 2]

Example 2

Input: “23-45”

1
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]

代码

这道题跟Unique Binary Search Trees II思路类似,都是利用分治的思想,可对照理解

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
public class Solution {
public List<Integer> diffWaysToCompute(String input) {
if(input == null || input.length() == 0) return new ArrayList<Integer>();

List<Integer> res = new ArrayList<>();

for(int i = 0; i < input.length(); i++){
char ch = input.charAt(i);
//字符ch为+、-、*,可以采用分治的方法将input在ch分为左右两部分,递归计算
if(ch == '-' || ch == '+' || ch == '*'){
List<Integer> leftList = diffWaysToCompute(input.substring(0, i));
List<Integer> rightList = diffWaysToCompute(input.substring(i+1));

for(int left : leftList){
for(int right : rightList){
switch(ch){
case '-': res.add(left - right);
break;
case '+': res.add(left + right);
break;
case '*': res.add(left * right);
break;
}
}
}
}
}
//数字
if(res.size() == 0) res.add(Integer.valueOf(input));

return res;
}
}