Skip to content

Commit 635d5cb

Browse files
authored
Create number-of-subsequences-with-odd-sum.py
1 parent 9d180db commit 635d5cb

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
# combinatorics, fast exponentiation
5+
class Solution(object):
6+
def subsequenceCount(self, nums):
7+
"""
8+
:type nums: List[int]
9+
:rtype: int
10+
"""
11+
MOD = 10**9+7
12+
# 2^(odd-1)*2^even = 2^(len(nums)-1)
13+
return pow(2, len(nums)-1, MOD) if any(x%2 for x in nums) else 0
14+
15+
16+
# Time: O(n)
17+
# Space: O(1)
18+
# dp
19+
class Solution2(object):
20+
def subsequenceCount(self, nums):
21+
"""
22+
:type nums: List[int]
23+
:rtype: int
24+
"""
25+
MOD = 10**9+7
26+
dp = [0]*2
27+
for x in nums:
28+
dp = [(dp[i]+dp[i^(x%2)]+int(x%2 == i))%MOD for i in xrange(2)]
29+
return dp[1]

0 commit comments

Comments
 (0)