2466. Count Ways To Build Good Strings #1031
-
Topics: Given the integers
This can be performed any number of times. A good string is a string constructed by the above process having a length between Return the number of different good strings that can be constructed satisfying these properties. Since the answer can be large, return it modulo Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to focus on constructing strings of different lengths and counting the number of valid strings that meet the given conditions. Let's break down the approach: Problem Breakdown
Solution Steps
Let's implement this solution in PHP: 2466. Count Ways To Build Good Strings <?php
function countGoodStrings($low, $high, $zero, $one) {
$MOD = 1000000007;
// Initialize dp array with size (high + 1), since we need to calculate lengths from 0 to high
$dp = array_fill(0, $high + 1, 0);
// Base case: one way to create a string of length 0 (empty string)
$dp[0] = 1;
// Fill dp array using the recurrence relation
for ($i = 1; $i <= $high; $i++) {
if ($i - $zero >= 0) {
$dp[$i] = ($dp[$i] + $dp[$i - $zero]) % $MOD;
}
if ($i - $one >= 0) {
$dp[$i] = ($dp[$i] + $dp[$i - $one]) % $MOD;
}
}
// Calculate the result as the sum of dp[i] for i in the range [low, high]
$result = 0;
for ($i = $low; $i <= $high; $i++) {
$result = ($result + $dp[$i]) % $MOD;
}
return $result;
}
// Example Usage
$low = 3;
$high = 3;
$zero = 1;
$one = 1;
echo countGoodStrings($low, $high, $zero, $one); // Output: 8
$low = 2;
$high = 3;
$zero = 1;
$one = 2;
echo countGoodStrings($low, $high, $zero, $one); // Output: 5
?> Explanation:
Time Complexity:
Thus, the overall time complexity is ** O(high) **, which is efficient enough for the input limits. Space Complexity:
This solution efficiently solves the problem within the constraints. |
Beta Was this translation helpful? Give feedback.
We need to focus on constructing strings of different lengths and counting the number of valid strings that meet the given conditions. Let's break down the approach:
Problem Breakdown
State Definition:
Let
dp[i]
represent the number of valid strings of lengthi
that can be constructed using the providedzero
andone
values.Recurrence Relation:
i
, we can append either:zero
consecutive0
s, so the previous string would be of lengthi-zero
, and we would adddp[i-zero]
ways.one
consecutive1
s, so the previous string would be of lengthi-one
, and we would adddp[i-one]
ways.The recurrence relation becomes:
dp[i] = dp[i - zero] + dp[i - one] (mod 109 + 7)
Base Case: