Skip to content

Commit 061f45c

Browse files
committed
feat(LeetCode): ✨ add diffWaysToCompute (lc. 0241)
1 parent 7f3bfbd commit 061f45c

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { diffWaysToCompute } from './0241-diffWaysToCompute'
2+
3+
it.each(
4+
// prettier-ignore
5+
[
6+
[
7+
"2-1-1",
8+
[0,2]
9+
],
10+
[
11+
"2*3-4*5",
12+
[-34,-14,-10,-10,10]
13+
]
14+
]
15+
)('should work %#', (input, output) => {
16+
expect(sort(diffWaysToCompute(input))).toMatchObject(sort(output))
17+
})
18+
19+
const sort = (nums: number[]) => nums.sort((a, b) => a - b)
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* {@link https://leetcode.com/problems/different-ways-to-add-parentheses/ | 241. Different Ways to Add Parentheses}
3+
*
4+
* Topics: Math | String | Dynamic Programming | Recursion | Memoization
5+
*/
6+
export function diffWaysToCompute(expression: string): number[] {
7+
const cache = new Map<string, number[]>()
8+
const operators = new Set(['+', '-', '*'])
9+
10+
const dfs = (exp: string): number[] => {
11+
if (!exp) return []
12+
if (cache.has(exp)) return cache.get(exp)!
13+
if (Number.isInteger(+exp)) return [+exp]
14+
15+
const res: number[] = []
16+
const n = exp.length
17+
18+
for (let i = 0; i < n; i++) {
19+
const ch = exp[i]
20+
if (!operators.has(ch)) continue
21+
22+
const [left, right] = [dfs(exp.slice(0, i)), dfs(exp.slice(i + 1))]
23+
for (const x of left) {
24+
for (const y of right) {
25+
if (ch === '+') res.push(x + y)
26+
if (ch === '-') res.push(x - y)
27+
if (ch === '*') res.push(x * y)
28+
}
29+
}
30+
}
31+
32+
cache.set(exp, res)
33+
34+
return res
35+
}
36+
37+
return dfs(expression)
38+
}

0 commit comments

Comments
 (0)