Skip to content

241. Different Ways to Add Parentheses #571

Discussion options

You must be logged in to vote

We can use recursion combined with memoization to store previously computed results for sub-expressions, as this avoids redundant calculations and optimizes the solution.

Approach:

  1. Recursion:

    • For each operator in the string (+, -, *), we split the expression at that operator.
    • Recursively compute the left and right parts of the expression.
    • Combine the results of both parts using the operator.
  2. Memoization:

    • Store the results of sub-expressions in an associative array to avoid recalculating the same sub-expression multiple times.
  3. Base Case:

    • If the expression contains only a number (i.e., no operators), return that number as the result.

Example Walkthrough:

For the input "2*3-4*5":

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@mah-shamim
Comment options

mah-shamim Sep 19, 2024
Maintainer Author

@basharul-siddike
Comment options

Answer selected by mah-shamim
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested medium Difficulty
2 participants