File tree 2 files changed +32
-0
lines changed
2 files changed +32
-0
lines changed Original file line number Diff line number Diff line change 222
222
238|[ Product of Array Except Self] ( ./0238-product-of-array-except-self.js ) |Medium|
223
223
239|[ Sliding Window Maximum] ( ./0239-sliding-window-maximum.js ) |Hard|
224
224
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|
225
226
242|[ Valid Anagram] ( ./0242-valid-anagram.js ) |Easy|
226
227
257|[ Binary Tree Paths] ( ./0257-binary-tree-paths.js ) |Easy|
227
228
258|[ Add Digits] ( ./0258-add-digits.js ) |Easy|
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments