241. Different Ways to Add Parentheses #571
-
Topics: Given a string 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 Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
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:
Example Walkthrough:For the input
Let's implement this solution in PHP: 241. Different Ways to Add Parentheses <?php
class Solution {
/**
* @var array
*/
private $memo = [];
/**
* @param String $expression
* @return Integer[]
*/
public function diffWaysToCompute($expression) {
// Call the recursive function to compute results
return $this->compute($expression);
}
/**
* @param $expression
* @return array|mixed
*/
private function compute($expression) {
// Check if the result for this expression is already computed
if (isset($this->memo[$expression])) {
return $this->memo[$expression];
}
$results = [];
// Check if the expression is a single number
if (is_numeric($expression)) {
$results[] = (int)$expression;
} else {
// Iterate through the expression
for ($i = 0; $i < strlen($expression); $i++) {
$char = $expression[$i];
// If the character is an operator
if ($char == '+' || $char == '-' || $char == '*') {
// Split the expression into two parts
$left = substr($expression, 0, $i);
$right = substr($expression, $i + 1);
// Compute all results for left and right parts
$leftResults = $this->compute($left);
$rightResults = $this->compute($right);
// Combine the results based on the operator
foreach ($leftResults as $leftResult) {
foreach ($rightResults as $rightResult) {
if ($char == '+') {
$results[] = $leftResult + $rightResult;
} elseif ($char == '-') {
$results[] = $leftResult - $rightResult;
} elseif ($char == '*') {
$results[] = $leftResult * $rightResult;
}
}
}
}
}
}
// Memoize the result for the current expression
$this->memo[$expression] = $results;
return $results;
}
}
// Example usage
$solution = new Solution();
$expression1 = "2-1-1";
$expression2 = "2*3-4*5";
print_r($solution->diffWaysToCompute($expression1)); // Output: [0, 2]
print_r($solution->diffWaysToCompute($expression2)); // Output: [-34, -14, -10, -10, 10]
?> Explanation:
This approach ensures that you efficiently compute all possible results by leveraging memoization to avoid redundant computations. |
Beta Was this translation helpful? Give feedback.
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:
Recursion:
+
,-
,*
), we split the expression at that operator.Memoization:
Base Case:
Example Walkthrough:
For the input
"2*3-4*5"
: