# Middle-题目38：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]

public class Solution {
public  List<Integer> diffWaysToCompute(String input) {
List<Integer> list=new ArrayList<Integer>();
if(isNumeric(input))  // if input is an integer
else {
for(int i=0;i<input.length();i++) {
char op=input.charAt(i);
if(op == '+' || op == '-' || op == '*') {
List<Integer> leftList = diffWaysToCompute(input.substring(0,i));
List<Integer> rightList = diffWaysToCompute(input.substring(i+1));
for(Integer j : leftList)
for(Integer k : rightList)
}
}
}
return list;
}
private  Integer operate(int a, char op, int b) {
if(op=='+')
return a+b;
else if(op=='-')
return a-b;
else
return a*b;
}
public boolean isNumeric(String str){
for(int i=str.length();--i>=0;){
int chr=str.charAt(i);
if(chr<48 || chr>57)
return false;
}
return true;
}
}

9ms,beats 27.25%,众数8ms,21.40%
cmershen的碎碎念：

• 本文已收录于以下专栏：

举报原因： 您举报文章：Middle-题目38：241. Different Ways to Add Parentheses 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)