
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).
1class Solution {
2 public static final int MOD = 1000000007;
3 public int numWays(String[] words, String target) {
4 int m = words[0].length(), t = target.length();
5 int[][] dp = new int[t+1][m+1];
6 int[][] count = new int[m][26];
7
8 for (String word : words)
9 for (int i = 0; i < m; ++i)
10 count[i][word.charAt(i) - 'a']++;
11
12 for (int j = 0; j <= m; ++j)
13 dp[0][j] = 1;
14
15 for (int i = 1; i <= t; ++i) {
16 for (int j = 1; j <= m; ++j) {
17 dp[i][j] = dp[i][j-1];
18 if (count[j-1][target.charAt(i-1) - 'a'] > 0)
19 dp[i][j] += (long)dp[i-1][j-1] * count[j-1][target.charAt(i-1) - 'a'] % MOD;
20 dp[i][j] %= MOD;
21 }
22 }
23
24 return dp[t][m];
25 }
26}
27The Java solution employs a similar dynamic programming approach as the other solutions. It uses a 2D `dp` array to store the number of ways to form segments of the target from the columns of words, utilizing a character count array to facilitate DP transitions. The result is computed modulo 10^9 + 7 due to potential large output values.
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).
This solution employs a recursive depth-first search (`dfs`) with memoization. The function `dfs(i, j)` returns the number of ways to form the target string starting from index `i` of the target and index `j` of a word in `words`. The memoized `dp` array stores results of overlapping subproblems to avoid recalculations.