|
| 1 | +package com.thealgorithms.dynamicprogramming; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +/** |
| 7 | + * This class provides a solution to the "All Construct" problem. |
| 8 | + * |
| 9 | + * The problem is to determine all the ways a target string can be constructed |
| 10 | + * from a given list of substrings. Each substring in the word bank can be used |
| 11 | + * multiple times, and the order of substrings matters. |
| 12 | + * |
| 13 | + * @author Hardvan |
| 14 | + */ |
| 15 | +public class AllConstruct { |
| 16 | + |
| 17 | + /** |
| 18 | + * Finds all possible ways to construct the target string using substrings |
| 19 | + * from the given word bank. |
| 20 | + * Time Complexity: O(n * m * k), where n = length of the target, |
| 21 | + * m = number of words in wordBank, and k = average length of a word. |
| 22 | + * |
| 23 | + * Space Complexity: O(n * m) due to the size of the table storing combinations. |
| 24 | + * |
| 25 | + * @param target The target string to construct. |
| 26 | + * @param wordBank A list of substrings that can be used to construct the target. |
| 27 | + * @return A list of lists, where each inner list represents one possible |
| 28 | + * way of constructing the target string using the given word bank. |
| 29 | + */ |
| 30 | + public static List<List<String>> allConstruct(String target, List<String> wordBank) { |
| 31 | + List<List<List<String>>> table = new ArrayList<>(target.length() + 1); |
| 32 | + |
| 33 | + for (int i = 0; i <= target.length(); i++) { |
| 34 | + table.add(new ArrayList<>()); |
| 35 | + } |
| 36 | + |
| 37 | + table.get(0).add(new ArrayList<>()); |
| 38 | + |
| 39 | + for (int i = 0; i <= target.length(); i++) { |
| 40 | + if (!table.get(i).isEmpty()) { |
| 41 | + for (String word : wordBank) { |
| 42 | + if (i + word.length() <= target.length() && |
| 43 | + target.substring(i, i + word.length()).equals(word)) { |
| 44 | + |
| 45 | + List<List<String>> newCombinations = new ArrayList<>(); |
| 46 | + for (List<String> combination : table.get(i)) { |
| 47 | + List<String> newCombination = new ArrayList<>(combination); |
| 48 | + newCombination.add(word); |
| 49 | + newCombinations.add(newCombination); |
| 50 | + } |
| 51 | + |
| 52 | + table.get(i + word.length()).addAll(newCombinations); |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + return table.get(target.length()); |
| 59 | + } |
| 60 | +} |
0 commit comments