
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).
1using System;
2
3public class Solution {
4 private const int MOD = 1000000007;
5
6 public int NumWays(string[] words, string target) {
7 int m = words[0].Length, t = target.Length;
8 int[,] dp = new int[t+1, m+1];
9 int[,] count = new int[m, 26];
10
11 foreach (var word in words)
12 for (int i = 0; i < m; ++i)
13 count[i, word[i] - 'a']++;
14
15 for (int j = 0; j <= m; ++j)
16 dp[0, j] = 1;
17
18 for (int i = 1; i <= t; ++i) {
19 for (int j = 1; j <= m; ++j) {
20 dp[i, j] = dp[i, j - 1];
21 if (count[j - 1, target[i - 1] - 'a'] > 0) {
22 dp[i, j] = (int)((dp[i, j] + (long)dp[i - 1, j - 1] *
23 count[j - 1, target[i - 1] - 'a']) % MOD);
24 }
25 }
26 }
27
28 return dp[t, m];
29 }
30}
31The C# solution applies a comparable dynamic programming methodology as showcased in different languages. It maintains a 2D DP array and employs a character frequency array to derive the number of ways to incrementally construct the target string.
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).
public class Solution {
private const int MOD = 1000000007;
private int[,] dp;
private int[,] count;
private int Dfs(string target, int i, int j, int m) {
if (i == target.Length) return 1;
if (j == m) return 0;
if (dp[i, j] != -1) return dp[i, j];
int res = Dfs(target, i, j + 1, m);
if (count[j, target[i] - 'a'] > 0) {
res = (int)((res + (long)count[j, target[i] - 'a'] * Dfs(target, i + 1, j + 1, m)) % MOD);
}
dp[i, j] = res;
return res;
}
public int NumWays(string[] words, string target) {
int m = words[0].Length;
dp = new int[target.Length, m + 1];
count = new int[m, 26];
Array.Fill(dp, -1);
foreach (var word in words)
for (int i = 0; i < m; ++i)
count[i, word[i] - 'a']++;
return Dfs(target, 0, 0, m);
}
}
The C# implementation uses a recursive strategy enhanced with a memoization technique. This solution avoids redundant calculations by leveraging a `dp` cache for previously computed results, reducing the time complexity drastically.