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]

tag: DFS

class Solution {
    public List<Integer> diffWaysToCompute(String input) {
        List<Integer> ans = new ArrayList<>();
        if (input == null || input.length() == 0) return ans;

        return dfs(input, new HashMap<String, List<Integer>>());
    }

    private List<Integer> dfs(String input, Map<String, List<Integer>> hash){
        if (hash.containsKey(input)){
            return hash.get(input);
        }

        List<Integer> temp = new ArrayList<>();
        for (int k = 0; k < input.length(); k++){
            char c = input.charAt(k);

            if (c == '+' || c == '-' || c == '*'){
                String input1 = input.substring(0, k);
                String input2 = input.substring(k + 1);

                List<Integer> temp1 = diffWaysToCompute(input1);
                List<Integer> temp2 = diffWaysToCompute(input2);

                for (int num1 : temp1){
                    for (int num2 : temp2){
                        if (c == '+'){
                            temp.add(num1 + num2);
                        }
                        else if (c == '-'){
                            temp.add(num1 - num2);
                        }
                        else if (c == '*'){
                            temp.add(num1 * num2);
                        }
                    }
                }
            }
        }

        if (temp.size() == 0){
            temp.add(Integer.valueOf(input));
        }

        hash.put(input, temp);

        return temp;
    }
}

results for ""

    No results matching ""