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:
Example 2[0, 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]
https://leetcode.com/problems/different-ways-to-add-parentheses/
public class Solution {
public Integer compute(Integer a, Integer b, char op){
if(op=='+') return a+b;
else if(op=='-')return a-b;
else if(op=='*')return a*b;
return 0;
}
public List<Integer> diffWaysToCompute(String input) {
List<Integer> res = new ArrayList<Integer>();
int len = input.length();
if(Character.isDigit(input.charAt(0))){
int i=0;
int number = input.charAt(i) - '0';
while(i+1<len && Character.isDigit(input.charAt(++i))){
number = number*10 + input.charAt(i)-'0';
}
//edge case for recusrion, input is just a number, no operator.
if(i==len-1){
res.add(number);
return res;
}
}
//recursion dp, res(i,j) = res(i,k) op res(k+2,j), op = input[k+1].
for(int k=0;k<len;++k){
if(Character.isDigit(input.charAt(k)) == false){
List<Integer> left = new ArrayList<Integer>();
List<Integer> right = new ArrayList<Integer>();
left = diffWaysToCompute(input.substring(0,k));
right = diffWaysToCompute(input.substring(k+1));
for(int i=0;i<left.size();++i){
for(int j=0;j<right.size();++j){
char op = input.charAt(k);
Integer subres = compute(left.get(i), right.get(j), op);
res.add(subres);
}
}
}
}
return res;
}
}
No comments:
Post a Comment