241. Different Ways to Add Parentheses

Given a string expression of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. You may return the answer in any order.

The test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed 104.

题意:给定字符串只含有+-*,可以改变计算顺序(加括号),求一共有多少种可能(不用去重)

思路:枚举最后一次操作符,即枚举表达式数的根节点。递归求出左子树的可能情况和右子树的可能情况。

技巧:把每一个数和操作数都放到一个数组中,可以用下标访问。

class Solution {
    List<String>expr=new ArrayList<>();
    public List<Integer> diffWaysToCompute(String input) {
          int n=input.length();
          for(int i=0;i<n;i++){
              char c=input.charAt(i);
              if(Character.isDigit(c)){
                  int j=i,x=0;
                  while(j<n&&Character.isDigit(input.charAt(j)))x=x*10+(input.charAt(j++)-'0');
                  i=j-1;
                  expr.add(String.valueOf(x));
              }else expr.add(String.valueOf(c));
          }
          return dfs(0,expr.size()-1);
    }
    List<Integer>dfs(int l,int r){
        List<Integer>res=new ArrayList<>();
        if(l==r)res.add(Integer.valueOf(expr.get(l)));
        else{
            for(int i=l+1;i<r;i+=2){
                List<Integer>left=dfs(l,i-1);
                List<Integer>right=dfs(i+1,r);
                for(int x:left){
                    for(int y:right){
                        int z=0;
                        if(expr.get(i).equals("+"))z=x+y;
                        else if(expr.get(i).equals("-"))z=x-y;
                        else z=x*y;
                        res.add(z);
                    }
                }
            }
        }
        return res;
    }
}