241. Different Ways to Add Parentheses
Difficulty: Medium
Topics: Math, String, Dynamic Programming, Recursion, Memoization
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.
Example 1:
((2-1)-1) = 0 (2-(1-1)) = 2
Example 2:
(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
Constraints:
Solution:
We can use recursion combined with memoization to store previously computed results for sub-expressions, as this avoids redundant calculations and optimizes the solution.
Recursion:
Memoization:
Base Case:
For the input "2*3-4*5":
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) { ... ... ... /** * go to ./solution.php */ } /** * @param $expression * @return array|mixed */ private function compute($expression) { ... ... ... /** * go to ./solution.php */ } } // 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] ?>
This approach ensures that you efficiently compute all possible results by leveraging memoization to avoid redundant computations.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
以上是. Different Ways to Add Parentheses的详细内容。更多信息请关注PHP中文网其他相关文章!