LeetCode 241: Different Ways to Add Parentheses

Problem Description

Explanation

To solve this problem, we can use a divide and conquer approach combined with recursion. We will iterate through the expression and whenever we encounter an operator, we will split the expression into two parts around that operator. We will then recursively calculate the results for both parts and combine them in all possible ways according to the operator encountered.

This recursive approach will generate all possible ways to group numbers and operators. We will keep track of the intermediate results for each combination of grouping. Finally, we return all possible results.

Time Complexity: The time complexity of this approach is exponential as we are exploring all possible grouping combinations. It can be represented as O(4^n) where n is the number of operators in the expression.

Space Complexity: The space complexity is also exponential due to the recursive nature of the algorithm and the need to store intermediate results. It can be represented as O(4^n).

Solutions

class Solution {
    public List<Integer> diffWaysToCompute(String expression) {
        List<Integer> result = new ArrayList<>();
        for (int i = 0; i < expression.length(); i++) {
            char c = expression.charAt(i);
            if (c == '+' || c == '-' || c == '*') {
                List<Integer> left = diffWaysToCompute(expression.substring(0, i));
                List<Integer> right = diffWaysToCompute(expression.substring(i + 1));
                for (int num1 : left) {
                    for (int num2 : right) {
                        if (c == '+') {
                            result.add(num1 + num2);
                        } else if (c == '-') {
                            result.add(num1 - num2);
                        } else if (c == '*') {
                            result.add(num1 * num2);
                        }
                    }
                }
            }
        }
        if (result.isEmpty()) {
            result.add(Integer.parseInt(expression));
        }
        return result;
    }
}

Loading editor...