# Middle-题目38：241. Different Ways to Add Parentheses

61人阅读 评论(0)

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的碎碎念：

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：56732次
• 积分：3211
• 等级：
• 排名：第10678名
• 原创：270篇
• 转载：53篇
• 译文：0篇
• 评论：7条
文章分类
最新评论