| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.DifferentWaysToAddParentheses; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class DifferentWaysToAddParenthesesRecursive : IDifferentWaysToAddParentheses |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(3^n) |
| | 19 | | /// Space complexity - O(3^n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="expression"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public IList<int> DiffWaysToCompute(string expression) |
| 361 | 24 | | { |
| 361 | 25 | | var results = new List<int>(); |
| | 26 | |
|
| 361 | 27 | | if (int.TryParse(expression, out var number)) |
| 241 | 28 | | { |
| 241 | 29 | | results.Add(number); |
| | 30 | |
|
| 241 | 31 | | return results; |
| | 32 | | } |
| | 33 | |
|
| 1326 | 34 | | for (var i = 0; i < expression.Length; i++) |
| 543 | 35 | | { |
| 543 | 36 | | if (char.IsDigit(expression[i])) |
| 365 | 37 | | { |
| 365 | 38 | | continue; |
| | 39 | | } |
| | 40 | |
|
| 178 | 41 | | var leftResults = DiffWaysToCompute(expression[..i]); |
| 178 | 42 | | var rightResults = DiffWaysToCompute(expression[(i + 1)..]); |
| | 43 | |
|
| 974 | 44 | | foreach (var leftResult in leftResults) |
| 220 | 45 | | { |
| 483 | 46 | | results.AddRange(rightResults.Select(rightResult => expression[i] switch |
| 483 | 47 | | { |
| 104 | 48 | | '+' => leftResult + rightResult, |
| 135 | 49 | | '-' => leftResult - rightResult, |
| 24 | 50 | | '*' => leftResult * rightResult, |
| 0 | 51 | | _ => 0 |
| 483 | 52 | | })); |
| 220 | 53 | | } |
| 178 | 54 | | } |
| | 55 | |
|
| 120 | 56 | | return results; |
| 361 | 57 | | } |
| | 58 | | } |