
Sponsored
Sponsored
This approach utilizes dynamic programming along with a frequency table to keep track of the count of each character at each column index across the given words. We calculate ways to form the target string by building up solutions to subproblems of forming prefixes of the target string using the letter frequency information efficiently.
Time Complexity: O(n*m + m*t), where n is the number of words, m is the length of each word, and t is the length of the target string.
Space Complexity: O(m*t).
1#include <stdio.h>
2#include <string.h>
3#define MOD 1000000007
4
5int numWays(char **words, int wordsSize, char *target) {
6 int wordLen = strlen(words[0]);
7 int targetLen = strlen(target);
8 int dp[targetLen+1][wordLen+1];
9 int count[wordLen][26];
10 memset(count, 0, sizeof(count));
11
12 for (int i = 0; i < wordsSize; ++i) {
13 for (int j = 0; j < wordLen; ++j) {
14 count[j][words[i][j] - 'a']++;
15 }
16 }
17
18 for (int i = 0; i <= targetLen; +i++) {
19 dp[i][0] = i == 0 ? 1 : 0;
20 }
21 for (int j = 1; j <= wordLen; ++j) {
22 dp[0][j] = 1;
23 }
24
25 for (int i = 1; i <= targetLen; ++i) {
26 for (int j = 1; j <= wordLen; ++j) {
27 dp[i][j] = dp[i][j-1];
28 int charIndex = target[i-1] - 'a';
29 dp[i][j] += (long long)dp[i-1][j-1] * count[j-1][charIndex] % MOD;
30 dp[i][j] %= MOD;
31 }
32 }
33
34 return dp[targetLen][wordLen];
35}
36This solution constructs a DP table where `dp[i][j]` represents the number of ways to form the first `i` characters of the target using the first `j` characters (positions) of the words. The `count` table stores how many times each character appears at each position in `words`. We update the DP table row by row for each position in the target by combining counts from the `count` table and previous DP states.
This approach uses memoization to optimize the recursion while forming the target. We compute ways from each index of target and position of words and save computed results to avoid redundant calculations. This approach is effective in reducing the exponential time complexity without deep overlapping subproblems.
Time Complexity: O(n*m + m*t), optimized with memoization.
Space Complexity: O(m*t).
1
This Python solution applies memoization on top of a recursive depth-first search approach. By storing results in a memo array (`dp`), it prevents recalculated paths for `dfs(i, j)`, ensuring optimal performance without overlapping computations.