Leetcode Problem 1639. Number of Ways to Form a Target String Given a Dictionary

1639. Number of Ways to Form a Target String Given a Dictionary

Leetcode Solutions

Bottom-up Dynamic Programming

Algorithm

  1. Initialize a matrix charOccurrences with zeros.
  2. Iterate over each column col and each word in words to fill charOccurrences with the count of each character.
  3. Initialize a DP matrix dp with zeros.
  4. Set dp[0][0] = 1 as the base case.
  5. For each length from 0 to targetLength, and for each col from 0 to wordLength - 1, do the following:
    • If length < targetLength, update dp[length + 1][col + 1] by adding charOccurrences[target[length] - 'a'][col] * dp[length][col].
    • Update dp[length][col + 1] by adding dp[length][col].
  6. Return dp[targetLength][wordLength] as the result.
UML Thumbnail

Top-Down Dynamic Programming (Memoization)

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...