Skip to content

Commit 89f2da0

Browse files
committed
[LeetCode Sync] Runtime - 622 ms (55.99%), Memory - 18 MB (74.60%)
1 parent 58af9ae commit 89f2da0

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<p>Given an integer array <code>nums</code>, return <code>true</code> <em>if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or </em><code>false</code><em> otherwise</em>.</p>
2+
3+
<p>&nbsp;</p>
4+
<p><strong class="example">Example 1:</strong></p>
5+
6+
<pre>
7+
<strong>Input:</strong> nums = [1,5,11,5]
8+
<strong>Output:</strong> true
9+
<strong>Explanation:</strong> The array can be partitioned as [1, 5, 5] and [11].
10+
</pre>
11+
12+
<p><strong class="example">Example 2:</strong></p>
13+
14+
<pre>
15+
<strong>Input:</strong> nums = [1,2,3,5]
16+
<strong>Output:</strong> false
17+
<strong>Explanation:</strong> The array cannot be partitioned into equal sum subsets.
18+
</pre>
19+
20+
<p>&nbsp;</p>
21+
<p><strong>Constraints:</strong></p>
22+
23+
<ul>
24+
<li><code>1 &lt;= nums.length &lt;= 200</code></li>
25+
<li><code>1 &lt;= nums[i] &lt;= 100</code></li>
26+
</ul>
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution:
2+
def canPartition(self, nums: List[int]) -> bool:
3+
# m, mod = divmod(sum(nums), 2)
4+
5+
# # if the sum is odd it can't be split into two subsets
6+
# if mod:
7+
# return False
8+
9+
# n = len(nums)
10+
# dp = [[False] * (m + 1) for _ in range(n + 1)]
11+
# dp[0][0] = True
12+
13+
# for i, num in enumerate(nums, 1):
14+
# for j in range(m + 1):
15+
# dp[i][j] = dp[i - 1][j] or (j >= num and dp[i - 1][j - num])
16+
17+
# return dp[-1][-1]
18+
19+
m, mod = divmod(sum(nums), 2)
20+
21+
# if the sum is odd it can't be split into two subsets
22+
if mod:
23+
return False
24+
25+
dp = [True] + [False] * m
26+
for num in nums:
27+
for j in range(m, num - 1, -1):
28+
dp[j] = dp[j] or dp[j - num]
29+
return dp[-1]

0 commit comments

Comments
 (0)