-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path416.py
50 lines (30 loc) · 1.04 KB
/
416.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# leetcode 416 分割等和子集
# 单数组版本
class Solution:
def canPartition(self, nums: List[int]) -> bool:
_sum = sum(nums)
if _sum % 2 != 0:
return False
target = _sum // 2
dp = [0 for _ in range(target + 1)]
for num in nums:
for j in range(target, num - 1, -1):
dp[j] = max(dp[j], dp[j - num] + num)
return dp[-1] == target
# 二维数组版本
class Solution:
def canPartition(self, nums: List[int]) -> bool:
_sum = sum(nums)
if _sum % 2 != 0:
return False
target = _sum // 2
dp = [[False] * (target + 1) for _ in range(len(nums) + 1)]
for i in range(len(nums) + 1):
dp[i][0] = True
for i in range(1, len(nums) + 1):
for j in range(1, target + 1):
if j < nums[i - 1]:
dp[i][j] = dp[i - 1][j]
else:
dp[i][j] = dp[i - 1][j] or dp[i - 1][j - nums[i - 1]]
return dp[-1][-1]