Leetcode-2533

Number of Good Binary Strings

Time complexity: $O(maxLength)$

 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
#include <iostream>
#include <vector>

const int M = 1'000'000'007;

class Solution {
public:
    int goodBinaryStrings(int minLength, int maxLength, int oneGroup, int zeroGroup) {
        std::vector<int> dp(maxLength + 1, 0);
        if (zeroGroup > oneGroup) {
            std::swap(zeroGroup, oneGroup);
        }
        
        int n = std::min(maxLength + 1, oneGroup + zeroGroup);
        for (int i = 0; i < n; i += zeroGroup) {
            dp[i] = 1;
        }
        dp[oneGroup] += 1;
        
        for (int i = oneGroup + 1; i <= maxLength; ++i) {
            dp[i] = (dp[i - zeroGroup] + dp[i - oneGroup]) % M;
        }
        
        long long res = 0;
        for (int i = minLength; i <= maxLength; ++i) {
            res += dp[i];
        }
        
        return res % M;
    }
};

Leetcode-2533

Licensed under CC BY-NC-SA 4.0