Skip to content

Commit 626b019

Browse files
committedFeb 6, 2025
Add solution #282
1 parent e2399e0 commit 626b019

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,7 @@
218218
273|[Integer to English Words](./0273-integer-to-english-words.js)|Hard|
219219
274|[H-Index](./0274-h-index.js)|Medium|
220220
278|[First Bad Version](./0278-first-bad-version.js)|Medium|
221+
282|[Expression Add Operators](./0282-expression-add-operators.js)|Hard|
221222
283|[Move Zeroes](./0283-move-zeroes.js)|Easy|
222223
290|[Word Pattern](./0290-word-pattern.js)|Easy|
223224
295|[Find Median from Data Stream](./0295-find-median-from-data-stream.js)|Hard|
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* 282. Expression Add Operators
3+
* https://leetcode.com/problems/expression-add-operators/
4+
* Difficulty: Hard
5+
*
6+
* Given a string num that contains only digits and an integer target, return all possibilities
7+
* to insert the binary operators '+', '-', and/or '*' between the digits of num so that the
8+
* resultant expression evaluates to the target value.
9+
*
10+
* Note that operands in the returned expressions should not contain leading zeros.
11+
*/
12+
13+
/**
14+
* @param {string} num
15+
* @param {number} target
16+
* @return {string[]}
17+
*/
18+
var addOperators = function(num, target) {
19+
const result = [];
20+
backtrack('', 0, 0, 0);
21+
return result;
22+
23+
function backtrack(expression, sum, prev, start) {
24+
if (start === num.length && sum === target) {
25+
result.push(expression);
26+
return;
27+
}
28+
for (let i = start, str = ''; i < num.length; i++) {
29+
str += num[i];
30+
const n = Number(str);
31+
if (!start) {
32+
backtrack(str, n, n, i + 1);
33+
if (str === '0') return;
34+
continue;
35+
}
36+
backtrack(expression + '*' + n, sum - prev + prev * n, prev * n, i + 1);
37+
backtrack(expression + '+' + n, sum + n, n, i + 1);
38+
backtrack(expression + '-' + n, sum - n, -n, i + 1);
39+
if (str === '0') return;
40+
}
41+
}
42+
};

0 commit comments

Comments
 (0)
Please sign in to comment.