Number of Ways to Form a Target String Given a Dictionary
1639. Number of Ways to Form a Target String Given a Dictionary
Difficulty: Hard
Topics: Array, String, Dynamic Programming
You are given a list of strings of the same length words and a string target.
Your task is to form target using the given words under the following rules:
- target should be formed from left to right.
- To form the ith character (0-indexed) of target, you can choose the kth character of the jth string in words if target[i] = words[j][k].
- Once you use the kth character of the jth string of words, you can no longer use the xth character of any string in words where x <= k. In other words, all characters to the left of or at index k become unusuable for every string.
- Repeat the process until you form the string target.
Notice that you can use multiple characters from the same string in words provided the conditions above are met.
Return the number of ways to form target from words. Since the answer may be too large, return it modulo 109 7.
Example 1:
- Input: words = ["acca","bbbb","caca"], target = "aba"
- Output: 6
-
Explanation: There are 6 ways to form target.
- "aba" -> index 0 ("acca"), index 1 ("bbbb"), index 3 ("caca")
- "aba" -> index 0 ("acca"), index 2 ("bbbb"), index 3 ("caca")
- "aba" -> index 0 ("acca"), index 1 ("bbbb"), index 3 ("acca")
- "aba" -> index 0 ("acca"), index 2 ("bbbb"), index 3 ("acca")
- "aba" -> index 1 ("caca"), index 2 ("bbbb"), index 3 ("acca")
- "aba" -> index 1 ("caca"), index 2 ("bbbb"), index 3 ("caca")
Example 2:
- Input: words = ["abba","baab"], target = "bab"
- Output: 4
-
Explanation: There are 4 ways to form target.
- "bab" -> index 0 ("baab"), index 1 ("baab"), index 2 ("abba")
- "bab" -> index 0 ("baab"), index 1 ("baab"), index 3 ("baab")
- "bab" -> index 0 ("baab"), index 2 ("baab"), index 3 ("baab")
- "bab" -> index 1 ("abba"), index 2 ("baab"), index 3 ("baab")
Constraints:
- 1 <= words.length <= 1000
- 1 <= words[i].length <= 1000
- All strings in words have the same length.
- 1 <= target.length <= 1000
- words[i] and target contain only lowercase English letters.
Hint:
- For each index i, store the frequency of each character in the ith row.
- Use dynamic programing to calculate the number of ways to get the target string using the frequency array.
Solution:
The problem requires finding the number of ways to form a target string from a dictionary of words, 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
-
Constraints:
- Words are of the same length.
- Characters in words can only be used in a left-to-right manner.
-
Challenges:
- Efficiently counting ways to form target due to large constraints.
- Avoid recomputation with memoization.
-
Modulo:
- Since the result can be large, all calculations are done modulo 109 7.
Approach
The solution uses:
-
Preprocessing:
- Count the frequency of each character at every position across all words.
-
Dynamic Programming:
- Use a 2D DP table to calculate the number of ways to form the target string.
Steps:
- Preprocess words into a frequency array (counts).
- Define a DP function to recursively find the number of ways to form target using the preprocessed counts.
Plan
-
Input Parsing:
- Accept words and target.
-
Preprocess:
- Create a counts array where counts[j][char] represents the frequency of char at position j in all words.
-
Dynamic Programming:
- Use a recursive function with memoization to compute the number of ways to form target using characters from valid positions in words.
-
Return the Result:
- Return the total count modulo 109 7.
Let's implement this solution in PHP: 1639. Number of Ways to Form a Target String Given a Dictionary
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
<!--?php
const
MOD = 1000000007;
/**
* @param String[] $words
* @param String $target
* @return Integer
*/
function
numWays(
$words
,
$target
) {
...
...
...
/**
* go to ./solution.php
*/
}
/**
* 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
) {
...
...
...
/**
* go to ./solution.php
*/
}
// 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
?-->
<h3>
Explanation:
</h3>
<ol>
<li>
<p><strong>Preprocessing Step</strong>:</p>
<ul>
<li>Build a counts
array
:
<ul>
<li>For each column in words,
count
the occurrences of each character.</li>
</ul>
</li>
<li>Example: If words = [
"acca"
,
"bbbb"
,
"caca"
],
for
the first column, counts[0] = {
'a'
: 1,
'b'
: 1,
'c'
: 1}.</li>
</ul>
</li>
<li>
<p><strong>Recursive DP</strong>:</p>
<ul>
<li>Define dp(i, j):
<ul>
<li>
i is the current index in target.</li>
<li>
j is the current position in words.</li>
</ul>
</li>
<li>Base Cases:
<ul>
<li>If i == len(target): Entire target formed →
return
1.</li>
<li>If j == len(words[0]): No more columns to
use
→
return
0.</li>
</ul>
</li>
<li>Recurrence:
<ul>
<li>Option 1: Use counts[j][target[i]] characters from position j.</li>
<li>Option 2: Skip position j.</li>
</ul>
</li>
</ul>
</li>
<li>
<p><strong>Optimization</strong>:</p>
<ul>
<li>Use a memoization table to store results of overlapping subproblems.</li>
</ul>
</li>
</ol>
<h3>
<strong>Example Walkthrough</strong>
</h3>
<p><strong>Input</strong>:<br><br>
words = [
"acca"
,
"bbbb"
,
"caca"
], target =
"aba"
</p>
<ol>
<li>
<p><strong>Preprocessing</strong>:</p>
<ul>
<li>counts[0] = {
'a'
: 2,
'b'
: 0,
'c'
: 1}</li>
<li>counts[1] = {
'a'
: 0,
'b'
: 3,
'c'
: 0}</li>
<li>counts[2] = {
'a'
: 1,
'b'
: 0,
'c'
: 2}</li>
<li>counts[3] = {
'a'
: 2,
'b'
: 0,
'c'
: 1}</li>
</ul>
</li>
<li>
<p><strong>DP Calculation</strong>:</p>
<ul>
<li>
dp(0, 0): How many ways to form
"aba"
starting from column 0.</li>
<li>Recursively calculate, combining the
use
of counts
and
skipping columns.</li>
</ul>
</li>
</ol>
<p><strong>Output</strong>: 6</p>
<h3>
<strong>Time Complexity</strong>
</h3>
<ol>
<li>
<strong>Preprocessing</strong>: <em><strong>O(n x m)</strong></em>, where n is the number of words
and
m is their length.</li>
<li>
<strong>Dynamic Programming</strong>: <em><strong>O(l x m)</strong></em>, where l is the length of the target.</li>
<li>
<strong>Total</strong>: <em><strong>O(n x m l x m)</strong></em>.</li>
</ol>
<h3>
<strong>Output
for
Example</strong>
</h3>
<ul>
<li>
<strong>Input</strong>:
words = [
"acca"
,
"bbbb"
,
"caca"
], target =
"aba"
</li>
<li>
<strong>Output</strong>: 6
</li>
</ul>
<p>This problem is a great example of combining preprocessing
and
dynamic programming to solve a combinatorial challenge efficiently.</p>
<p><strong>Contact Links</strong></p>
<p>If you found this series helpful, please consider giving the <strong>repository</strong> a star on GitHub
or
sharing the post on your favorite social networks ?. Your support would mean a lot to me!</p>
<p>If you want more helpful content like this, feel free to follow me:</p>
<ul>
<li><strong>LinkedIn</strong></li>
<li><strong>GitHub</strong></li>
</ul>
The above is the detailed content of Number of Ways to Form a Target String Given a Dictionary. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

RESTAPI design principles include resource definition, URI design, HTTP method usage, status code usage, version control, and HATEOAS. 1. Resources should be represented by nouns and maintained at a hierarchy. 2. HTTP methods should conform to their semantics, such as GET is used to obtain resources. 3. The status code should be used correctly, such as 404 means that the resource does not exist. 4. Version control can be implemented through URI or header. 5. HATEOAS boots client operations through links in response.

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

The main function of anonymous classes in PHP is to create one-time objects. 1. Anonymous classes allow classes without names to be directly defined in the code, which is suitable for temporary requirements. 2. They can inherit classes or implement interfaces to increase flexibility. 3. Pay attention to performance and code readability when using it, and avoid repeatedly defining the same anonymous classes.
