Similar Problems
Similar Problems not available
Number Of Ways To Form A Target String Given A Dictionary - Leetcode Solution
Companies:
LeetCode: Number Of Ways To Form A Target String Given A Dictionary Leetcode Solution
Difficulty: Hard
Topics: string dynamic-programming array
Problem Statement: Given a list of strings "words" and a string "target", find the number of ways that a target string can be formed by concatenating words from the list words, where each word can be used any number of times.
Example: Input: words = ["abc", "ab", "ac"], target = "abc" Output: 4 Explanation: The possible ways to form "abc" are:
- "abc" (using "abc")
- "ab" + "c" (using "ab" and "c")
- "ac" + "b" (using "ac" and "b")
- "a" + "b" + "c" (using "ab" and "ac")
Solution: This problem can be solved using dynamic programming. Let dp[i] be the number of ways to form a prefix of target of length i, and dp[0] is initialized as 1. We can then iterate through all possible prefixes of target and check if any word in the dictionary can be used to form that prefix. If a word can be used for a given prefix, we can add the number of ways to form the remaining prefix (which is target[0:i-len(word)]) to dp[i].
For example, for the input example above, the dp array would be: dp[0] = 1 (empty prefix) dp[1] = 1 ("a" can form "a") dp[2] = 2 ("ab" can be formed using "ab" or "a" and "b") dp[3] = 4 ("abc" can be formed using "abc", "ab" and "c", "ac" and "b", or "a", "b", and "c")
The final answer is dp[len(target)].
Here's the Python code for the solution:
def numWays(words, target): dp = [1] + [0] * len(target) for i in range(len(target)): for word in words: if len(word) <= i+1 and target[i+1-len(word):i+1] == word: dp[i+1] += dp[i-len(word)+1] return dp[len(target)]
The time complexity of this solution is O(len(target) * len(words) * max_word_length), where max_word_length is the maximum length of a word in words.
Number Of Ways To Form A Target String Given A Dictionary Solution Code
1