1639. Number of Ways to Form a Target String Given a Dictionary #1017
-
Topics: You are given a list of strings of the same length Your task is to form
Notice that you can use multiple characters from the same string in Return the number of ways to form Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The problem requires finding the number of ways to form a Key Points
ApproachThe solution uses:
Steps:
Plan
Let's implement this solution in PHP: 1639. Number of Ways to Form a Target String Given a Dictionary <?php
const MOD = 1000000007;
/**
* @param String[] $words
* @param String $target
* @return Integer
*/
function numWays($words, $target) {
$wordLength = strlen($words[0]);
$targetLength = strlen($target);
// Precompute character frequencies for each column
$counts = array_fill(0, $wordLength, array_fill(0, 26, 0));
foreach ($words as $word) {
for ($j = 0; $j < $wordLength; $j++) {
$counts[$j][ord($word[$j]) - ord('a')]++;
}
}
// Memoization table
$memo = array_fill(0, $targetLength, array_fill(0, $wordLength, -1));
return dp(0, 0, $counts, $target, $memo);
}
/**
* Helper function for DP
*
* @param $i
* @param $j
* @param $counts
* @param $target
* @param $memo
* @return float|int|mixed
*/
private function dp($i, $j, $counts, $target, &$memo) {
if ($i == strlen($target)) return 1; // Entire target formed
if ($j == count($counts)) return 0; // Out of bounds
if ($memo[$i][$j] != -1) return $memo[$i][$j];
$ways = dp($i, $j + 1, $counts, $target, $memo); // Skip this column
$charIndex = ord($target[$i]) - ord('a');
if ($counts[$j][$charIndex] > 0) {
$ways += dp($i + 1, $j + 1, $counts, $target, $memo) * $counts[$j][$charIndex];
$ways %= Solution::MOD;
}
return $memo[$i][$j] = $ways;
}
// Example Usage
$words = ["acca", "bbbb", "caca"];
$target = "aba";
echo numWays($words, $target) . "\n"; // Output: 6
$words = ["abba", "baab"];
$target = "bab";
echo numWays($words, $target) . "\n"; // Output: 4
?> Explanation:
Example WalkthroughInput:
Output: Time Complexity
Output for Example
This problem is a great example of combining preprocessing and dynamic programming to solve a combinatorial challenge efficiently. |
Beta Was this translation helpful? Give feedback.
The problem requires finding the number of ways to form a
target
string from a dictionary ofwords
, following specific rules about character usage. This is a combinatorial problem that can be solved efficiently using Dynamic Programming (DP) and preprocessing character frequencies.Key Points
target
due to large constraints.109 + 7
.Approach
The solution uses: