java中的动态规划字典练习自底向上方法
以下是我想解决的问题: 您将获得一个字典,即一组由m个字符串组成的S和一个单独的字符串t。您需要输出t可以分解的最小子字符串数,以便这些子字符串的并集是t,并且所有子字符串都属于字典。 例如: 输入: 五, 0111101000 1111001000 输出: 六, 我已经使用自顶向下的带记忆的方法(java)解决了这个问题:java中的动态规划字典练习自底向上方法,java,algorithm,dictionary,dynamic-programming,bottom-up,Java,Algorithm,Dictionary,Dynamic Programming,Bottom Up,以下是我想解决的问题: 您将获得一个字典,即一组由m个字符串组成的S和一个单独的字符串t。您需要输出t可以分解的最小子字符串数,以便这些子字符串的并集是t,并且所有子字符串都属于字典。 例如: 输入: 五, 0111101000 1111001000 输出: 六, 我已经使用自顶向下的带记忆的方法(java)解决了这个问题: publicstaticvoidmain(字符串[]args){ 扫描仪sc=新的扫描仪(System.in); int m=sc.nextInt(); 字符串[]s=新字
publicstaticvoidmain(字符串[]args){
扫描仪sc=新的扫描仪(System.in);
int m=sc.nextInt();
字符串[]s=新字符串[m];
对于(int i=0;i
}
我似乎找不到用自下而上的方法解决这个问题的方法。。。如果有人能告诉我如何用自下而上的方法解决这个问题,那就太好了请描述
r
和m
的语义。在memo
中,递归调用中不修改m
。请描述r
和m
的语义。在memo
中,递归调用中不修改m
。
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());
}