Skip to content

Commit 146f876

Browse files
committed
Sync LeetCode submission Runtime - 479 ms (76.27%), Memory - 71.8 MB (22.76%)
1 parent 61b4c46 commit 146f876

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-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: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Approach 2: Top Down Dynamic Programming - Memoization
2+
3+
# n = len(nums), m = subset_sum
4+
# Time: O(m * n)
5+
# Space: O(m * n)
6+
7+
class Solution:
8+
def canPartition(self, nums: List[int]) -> bool:
9+
@lru_cache(maxsize = None)
10+
def dfs(nums, n, subset_sum):
11+
if subset_sum == 0:
12+
return True
13+
if n == 0 or subset_sum < 0:
14+
return False
15+
result = (dfs(nums, n - 1, subset_sum - nums[n - 1]) or
16+
dfs(nums, n - 1, subset_sum))
17+
return result
18+
19+
total_sum = sum(nums)
20+
if total_sum % 2 != 0:
21+
return False
22+
23+
subset_sum = total_sum // 2
24+
n = len(nums)
25+
return dfs(tuple(nums), n - 1, subset_sum)

0 commit comments

Comments
 (0)