forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
number-of-good-binary-strings.py
54 lines (51 loc) · 1.6 KB
/
number-of-good-binary-strings.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
# Time: O(n), n = maxLength
# Space: O(w), w = max(oneGroup, zeroGroup)+1
# dp
class Solution(object):
def goodBinaryStrings(self, minLength, maxLength, oneGroup, zeroGroup):
"""
:type minLength: int
:type maxLength: int
:type oneGroup: int
:type zeroGroup: int
:rtype: int
"""
MOD = 10**9+7
result = 0
w = max(oneGroup, zeroGroup)+1
dp = [0]*w
for i in xrange(maxLength+1):
dp[i%w] = 1 if i == 0 else 0
if i-oneGroup >= 0:
dp[i%w] = (dp[i%w]+dp[(i-oneGroup)%w])%MOD
if i-zeroGroup >= 0:
dp[i%w] = (dp[i%w]+dp[(i-zeroGroup)%w])%MOD
if i >= minLength:
result = (result+dp[i%w])%MOD
return result
# Time: O(n), n = maxLength
# Space: O(w), w = max(oneGroup, zeroGroup)+1
# dp
class Solution(object):
def goodBinaryStrings(self, minLength, maxLength, oneGroup, zeroGroup):
"""
:type minLength: int
:type maxLength: int
:type oneGroup: int
:type zeroGroup: int
:rtype: int
"""
MOD = 10**9+7
result = 0
w = max(oneGroup, zeroGroup)+1
dp = [0]*w
dp[0] = 1
for i in xrange(maxLength+1):
if i >= minLength:
result = (result+dp[i%w])%MOD
if i+oneGroup <= maxLength:
dp[(i+oneGroup)%w] = (dp[(i+oneGroup)%w]+dp[i%w])%MOD
if i+zeroGroup <= maxLength:
dp[(i+zeroGroup)%w] = (dp[(i+zeroGroup)%w]+dp[i%w])%MOD
dp[i%w] = 0
return result