动态编程字典在java

时间:2015-10-29 17:34:23

标签: java algorithm dictionary dynamic-programming bottom-up

这是我要解决的问题: 给你一个字典,即一组m个字符串,一个单独的字符串t。您需要输出可以分解的最小子串数,这样这些子串的并集是t,并且所有子串都属于字典。 示例:

  

输入:

     

5

     

0 1 11 1101 000

     

1111001000

     

输出:

     

6

我已经使用自上而下的memoization方法解决了它(在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());
}

}

我似乎找不到使用自下而上方法解决这个问题的方法......如果有人能告诉我如何用自下而上的方法来解决它,那就太棒了

0 个答案:

没有答案
相关问题