We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent a8243a3 commit 72377f2Copy full SHA for 72377f2
scripts/algorithms/P/Partition Equal Subset Sum/Partition Equal Subset Sum.py
@@ -1,15 +1,14 @@
1
+// Runtime: 437 ms (Top 80.03%) | Memory: 18.00 MB (Top 70.21%)
2
+
3
class Solution:
4
def canPartition(self, nums: List[int]) -> bool:
- total = sum(nums)
- if total % 2: return False
5
- total //= 2
6
- leng = len(nums)
7
- dp = [[False] * (total + 1) for _ in range(leng + 1)]
8
-
9
- for i in range(leng + 1): dp[i][0] = True
10
- for i in range(1, leng + 1):
11
- for j in range(1, total + 1):
12
- dp[i][j] = dp[i-1][j]
13
- if j - nums[i-1] >= 0:
14
- dp[i][j] |= dp[i-1][j-nums[i-1]]
15
- return dp[leng][total]
+ dp, s = set([0]), sum(nums)
+ if s&1:
+ return False
+ for num in nums:
+ for curr in range(s>>1, num-1, -1):
+ if curr not in dp and curr-num in dp:
+ if curr == s>>1:
+ return True
+ dp.add(curr)
0 commit comments