File tree 1 file changed +42
-0
lines changed
1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Time: O(n * s), s is the sum of nums
2
+ # Space: O(s)
3
+
4
+ # Given a non-empty array containing only positive integers,
5
+ # find if the array can be partitioned into two subsets
6
+ # such that the sum of elements in both subsets is equal.
7
+ #
8
+ # Note:
9
+ # Both the array size and each of the array element will not exceed 100.
10
+ #
11
+ # Example 1:
12
+ #
13
+ # Input: [1, 5, 11, 5]
14
+ #
15
+ # Output: true
16
+ #
17
+ # Explanation: The array can be partitioned as [1, 5, 5] and [11].
18
+ # Example 2:
19
+ #
20
+ # Input: [1, 2, 3, 5]
21
+ #
22
+ # Output: false
23
+ #
24
+ # Explanation: The array cannot be partitioned into equal sum subsets.
25
+
26
+ class Solution (object ):
27
+ def canPartition (self , nums ):
28
+ """
29
+ :type nums: List[int]
30
+ :rtype: bool
31
+ """
32
+ s = sum (nums )
33
+ if s % 2 :
34
+ return False
35
+
36
+ dp = [False ] * (s / 2 + 1 )
37
+ dp [0 ] = True
38
+ for num in nums :
39
+ for i in xrange (1 , len (dp )):
40
+ if num <= i :
41
+ dp [i ] = dp [i ] or dp [i - num ]
42
+ return dp [- 1 ]
You can’t perform that action at this time.
0 commit comments