davegimo

Untitled

Jun 6th, 2022
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class MyClass {
  4.  
  5.  
  6. public static int count(String str, List<String> letters, Map<String, Integer> vocab) {
  7. System.out.println(str);
  8. if (str.isEmpty()) { // base case - a combination was found
  9. return 1;
  10. }
  11. if (vocab.containsKey(str)) { // result was already computed and present in the map
  12. System.out.println("trovato valore per " + str + ": " + vocab.get(str));
  13. return vocab.get(str);
  14. }
  15.  
  16. int count = 0;
  17.  
  18. for (String letter: letters) {
  19. System.out.println(str + "," + letter);
  20. if (str.startsWith(letter)) {
  21. count += count(str.substring(letter.length()), letters, vocab);
  22. }
  23. }
  24. vocab.put(str, count); // storing the total `count` into the map
  25. System.out.println(count);
  26. return count;
  27. }
  28.  
  29. public static void main(String[] args) {
  30.  
  31. List<String> letters = List.of("0", "00", "001", "010", "0010", "0100", "0110", "0001"); // binary letters
  32.  
  33. System.out.println(count("000100100010010000100100001001100", letters, new HashMap<>())); // DP
  34. //System.out.println(count("00100", letters)); // brute-force recursion
  35. }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment