-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution241.cs
45 lines (39 loc) · 1.26 KB
/
Solution241.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
namespace LeetCode.Solutions;
public class Solution241
{
/// <summary>
/// 241. Different Ways to Add Parentheses - Medium
/// <a href="https://leetcode.com/problems/different-ways-to-add-parentheses">See the problem</a>
/// </summary>
public IList<int> DiffWaysToCompute(string expression)
{
var result = new List<int>();
for (var i = 0; i < expression.Length; i++)
{
var c = expression[i];
if (c == '+' || c == '-' || c == '*')
{
var left = DiffWaysToCompute(expression.Substring(0, i));
var right = DiffWaysToCompute(expression.Substring(i + 1));
foreach (var l in left)
{
foreach (var r in right)
{
result.Add(c switch
{
'+' => l + r,
'-' => l - r,
'*' => l * r,
_ => throw new InvalidOperationException()
});
}
}
}
}
if (result.Count == 0)
{
result.Add(int.Parse(expression));
}
return result;
}
}