[LeetCode 241] Different Ways to Add Parentheses Java
题目:
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> res=new ArrayList<>(); for(int i=0;i<input.length();i++){ char ch=input.charAt(i); if(ch=='*'||ch=='-'||ch=='+'){ String leftSub=input.substring(0, i); String rightSub=input.substring(i+1); List<Integer> left=diffWaysToCompute(leftSub); List<Integer> right=diffWaysToCompute(rightSub); for(int j: left){ for(int k:right){ switch (ch) { case '+': res.add(j+k); break; case '-': res.add(j-k); break; case '*': res.add(j*k); break; } } } } } if(res.size()==0){ res.add(Integer.parseInt(input)); } return res; } }