Skip to content

Commit b651426

Browse files
committedFeb 21, 2025
Add solution #241
1 parent dedde99 commit b651426

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,7 @@
222222
238|[Product of Array Except Self](./0238-product-of-array-except-self.js)|Medium|
223223
239|[Sliding Window Maximum](./0239-sliding-window-maximum.js)|Hard|
224224
240|[Search a 2D Matrix II](./0240-search-a-2d-matrix-ii.js)|Medium|
225+
241|[Different Ways to Add Parentheses](./0241-different-ways-to-add-parentheses.js)|Medium|
225226
242|[Valid Anagram](./0242-valid-anagram.js)|Easy|
226227
257|[Binary Tree Paths](./0257-binary-tree-paths.js)|Easy|
227228
258|[Add Digits](./0258-add-digits.js)|Easy|
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* 241. Different Ways to Add Parentheses
3+
* https://leetcode.com/problems/different-ways-to-add-parentheses/
4+
* Difficulty: Medium
5+
*
6+
* Given a string expression of numbers and operators, return all possible results from
7+
* computing all the different possible ways to group numbers and operators. You may
8+
* return the answer in any order.
9+
*
10+
* The test cases are generated such that the output values fit in a 32-bit integer and
11+
* the number of different results does not exceed 104.
12+
*/
13+
14+
/**
15+
* @param {string} expression
16+
* @return {number[]}
17+
*/
18+
var diffWaysToCompute = function(expression) {
19+
const results = [];
20+
21+
for (let i = 0; i < expression.length; i++) {
22+
if ('+-*'.includes(expression[i])) {
23+
const left = diffWaysToCompute(expression.slice(0, i));
24+
const right = diffWaysToCompute(expression.slice(i + 1));
25+
left.forEach(l => right.forEach(r =>
26+
results.push(expression[i] === '+' ? l + r : expression[i] === '-' ? l - r : l * r)));
27+
}
28+
}
29+
30+
return results.length ? results : [+expression];
31+
};

0 commit comments

Comments
 (0)
Please sign in to comment.