Skip to content

Commit d3b9fc5

Browse files
committedMar 3, 2025
Add solution #494
1 parent 7e1e356 commit d3b9fc5

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -395,6 +395,7 @@
395395
491|[Non-decreasing Subsequences](./0491-non-decreasing-subsequences.js)|Medium|
396396
492|[Construct the Rectangle](./0492-construct-the-rectangle.js)|Easy|
397397
493|[Reverse Pairs](./0493-reverse-pairs.js)|Hard|
398+
494|[Target Sum](./0494-target-sum.js)|Medium|
398399
496|[Next Greater Element I](./0496-next-greater-element-i.js)|Easy|
399400
500|[Keyboard Row](./0500-keyboard-row.js)|Easy|
400401
501|[Find Mode in Binary Search Tree](./0501-find-mode-in-binary-search-tree.js)|Easy|

‎solutions/0494-target-sum.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* 494. Target Sum
3+
* https://leetcode.com/problems/target-sum/
4+
* Difficulty: Medium
5+
*
6+
* You are given an integer array nums and an integer target.
7+
*
8+
* You want to build an expression out of nums by adding one of the symbols '+' and '-' before
9+
* each integer in nums and then concatenate all the integers.
10+
*
11+
* For example, if nums = [2, 1], you can add a '+' before 2 and a '-' before 1 and concatenate
12+
* them to build the expression "+2-1".
13+
*
14+
* Return the number of different expressions that you can build, which evaluates to target.
15+
*/
16+
17+
/**
18+
* @param {number[]} nums
19+
* @param {number} target
20+
* @return {number}
21+
*/
22+
var findTargetSumWays = function(nums, target) {
23+
const map = new Map();
24+
25+
function dp(index, sum) {
26+
if (index === nums.length) {
27+
return sum === target ? 1 : 0;
28+
}
29+
const key = `${index},${sum}`;
30+
if (map.has(key)) {
31+
return map.get(key);
32+
}
33+
const r = dp(index + 1, sum + nums[index]) + dp(index + 1, sum - nums[index]);
34+
map.set(key, r);
35+
return r;
36+
}
37+
38+
return dp(0, 0);
39+
};

0 commit comments

Comments
 (0)
Please sign in to comment.