1

Here is the problem i want to solve: You are given a dictionary, i.e. a set S of m strings, and a separate string t. You are required to output the minimum number of substrings that t can be broken up to, such that the union of these substrings is t and all the substrings belong to the dictionary. Example:

Input:

5

0 1 11 1101 000

1111001000

Output:

6

I have solved it using the top-down with memoization approach (in java):

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int m = sc.nextInt();
    String[] s = new String[m];
    for(int i = 0; i < m; ++i){
    s[i] = sc.next();
    }
    String t = sc.next();        
    System.out.println(topDown(m, s, t));
}

public static int topDown(int m, String[] s, String t) {
    int r[] = new int[m + 1];
    for (int i = 0; i <= m; ++i) {
        r[i] = Integer.MAX_VALUE - 3;
    }
    return memo(m, s, t, r);
}

public static int memo(int m, String[] s, String t, int[] r) {
    int best = Integer.MAX_VALUE - 3;
    for (int i = 0; i < m; ++i) {
        if (t.equals(s[i])) {
            r[m] = 1;
            return 1;
        }
    }
    if (m == 0) {
        best = 0;
    } else {
        int a;
        for (String str : s) {
            if (t.endsWith(str)) {
                a = 1 + memo(m, s, replaceLast(t, str, ""), r);
                if (best > a)
                    best = a;
            }
        }
    }
    r[m] = best;
    return best;
}

public static String replaceLast(String string, String substring,
        String replacement) {
    int index = string.lastIndexOf(substring);
    if (index == -1)
        return string;
    return string.substring(0, index) + replacement
            + string.substring(index + substring.length());
}

}

I can't seem to find the way to solve this problem using the bottom-up approach... If someone could show me how to solve it with bottom-up it would be great

marcelovca90
  • 2,673
  • 3
  • 27
  • 34
  • Please describe the semantics of `r` and `m`. In `memo`, `m` is not modified in the recursive call. – Codor Aug 26 '16 at 06:24

0 Answers0