-
Notifications
You must be signed in to change notification settings - Fork 0
/
partition-equal-subset-sum.py
77 lines (65 loc) · 1.26 KB
/
partition-equal-subset-sum.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
class Solution(object):
# 递归+剪枝
def canPartition(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if not nums:
return False
total = sum(nums)
if total%2==1:
return False
total /= 2
n = len(nums)
nums = sorted(nums,reverse=True)
def dfs(index, remain):
if remain==0:
return True
if index<n and remain<nums[index]:
return False
for i in xrange(index,n):
if dfs(i+1, remain-nums[i]):
return True
return False
return dfs(0,total)
# 动态规划实现
def canPartition(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if not nums:
return False
total = 0
for i in nums:
total += i
if total%2==1:
return False
total /= 2
dp = [False]*(total+1)
dp[0] = True
for c in nums:
for i in xrange(total,c-1,-1):
if dp[i-c]:
dp[i] = True
return dp[-1]
# 动态规划,二维数组实现
def canPartition(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if not nums:
return False
total = sum(nums)
if total%2==1:
return False
total /= 2
n = len(nums)
dp = [False]*(total+1)
dp[0] = True
for i in xrange(n):
for j in xrange(total,nums[i]-1,-1):
dp[j] |= dp[j-nums[i]]
return dp[-1]