Skip to content

Commit ba2cb55

Browse files
committed
[LeetCode Sync] Runtime - 20 ms (91.05%), Memory - 17.9 MB (89.39%)
1 parent 2470abf commit ba2cb55

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<p>You are given an integer array <code>nums</code> and an integer <code>target</code>.</p>
2+
3+
<p>You want to build an <strong>expression</strong> out of nums by adding one of the symbols <code>&#39;+&#39;</code> and <code>&#39;-&#39;</code> before each integer in nums and then concatenate all the integers.</p>
4+
5+
<ul>
6+
<li>For example, if <code>nums = [2, 1]</code>, you can add a <code>&#39;+&#39;</code> before <code>2</code> and a <code>&#39;-&#39;</code> before <code>1</code> and concatenate them to build the expression <code>&quot;+2-1&quot;</code>.</li>
7+
</ul>
8+
9+
<p>Return the number of different <strong>expressions</strong> that you can build, which evaluates to <code>target</code>.</p>
10+
11+
<p>&nbsp;</p>
12+
<p><strong class="example">Example 1:</strong></p>
13+
14+
<pre>
15+
<strong>Input:</strong> nums = [1,1,1,1,1], target = 3
16+
<strong>Output:</strong> 5
17+
<strong>Explanation:</strong> There are 5 ways to assign symbols to make the sum of nums be target 3.
18+
-1 + 1 + 1 + 1 + 1 = 3
19+
+1 - 1 + 1 + 1 + 1 = 3
20+
+1 + 1 - 1 + 1 + 1 = 3
21+
+1 + 1 + 1 - 1 + 1 = 3
22+
+1 + 1 + 1 + 1 - 1 = 3
23+
</pre>
24+
25+
<p><strong class="example">Example 2:</strong></p>
26+
27+
<pre>
28+
<strong>Input:</strong> nums = [1], target = 1
29+
<strong>Output:</strong> 1
30+
</pre>
31+
32+
<p>&nbsp;</p>
33+
<p><strong>Constraints:</strong></p>
34+
35+
<ul>
36+
<li><code>1 &lt;= nums.length &lt;= 20</code></li>
37+
<li><code>0 &lt;= nums[i] &lt;= 1000</code></li>
38+
<li><code>0 &lt;= sum(nums[i]) &lt;= 1000</code></li>
39+
<li><code>-1000 &lt;= target &lt;= 1000</code></li>
40+
</ul>
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
class Solution:
2+
def findTargetSumWays(self, nums: List[int], target: int) -> int:
3+
sum_val = sum(nums)
4+
if sum_val < target or (sum_val - target) % 2:
5+
return 0
6+
7+
n = (sum_val - target) // 2
8+
dp = [0] * (n + 1)
9+
dp[0] = 1
10+
11+
for num in nums:
12+
for j in range(n, num - 1, -1):
13+
dp[j] += dp[j - num]
14+
15+
return dp[-1]

0 commit comments

Comments
 (0)