Algorithm 回溯算法必须从后面开始吗?
我用回溯算法解决了wordbreakII问题。 代码如下:Algorithm 回溯算法必须从后面开始吗?,algorithm,backtracking,Algorithm,Backtracking,我用回溯算法解决了wordbreakII问题。 代码如下: public static List<String> wordBreak(String s, Set<String> dict) { List<String> words = new ArrayList<String>(); int len = s.length(); for (int i = len -1; i >= 0; i--) { St
public static List<String> wordBreak(String s, Set<String> dict) {
List<String> words = new ArrayList<String>();
int len = s.length();
for (int i = len -1; i >= 0; i--) {
String last = s.substring(i, len); //get the last word and process the rest
if (dict.contains(last)) {
if (i == 0) {
words.add(last);
} else {
String remain = s.substring(0, i);
List<String> remainSet = wordBreak(remain, dict);
if (remainSet != null) {
for (String item : remainSet) {
words.add(item + " " + last);
}
}
}
}
}
return words;
}
公共静态列表分词(字符串s,Set dict){
List words=new ArrayList();
int len=s.length();
对于(int i=len-1;i>=0;i--){
String last=s.substring(i,len);//获取最后一个单词并处理其余单词
if(dict.contains(last)){
如果(i==0){
添加(最后一个);
}否则{
字符串剩余=s.子字符串(0,i);
列表remainSet=wordBreak(保留,dict);
如果(重新插入!=null){
用于(字符串项:重新插入){
添加(项目+“”+最后一项);
}
}
}
}
}
返回单词;
}
如果我尝试从前面处理,结果应该是相同的
public static List<String> wordBreakFront(String s, Set<String> dict) {
List<String> words = new ArrayList<String>();
int len = s.length();
for (int i = 1; i <= len; i++) {
String front = s.substring(0, i);
if (dict.contains(front)) {
if (i == len) {
words.add(front);
} else {
//get the front word and process the rest.
String remain = s.substring(i, len);
List<String> remainSet = wordBreak(remain, dict);
if (remainSet != null) {
for (String item : remainSet) {
words.add(front + " " + item);
}
}
}
}
}
return words;
}
公共静态列表wordBreakFront(字符串s,Set dict){
List words=new ArrayList();
int len=s.length();
对于(int i=1;i在最坏的情况下,它们的时间复杂度都是指数级的。幸运的是,第一个通过了,第二个失败了(如果将输入的单词和字典中的所有单词颠倒过来,第一个单词会工作得太长).这似乎只解决了寻找可能的单词的问题。这个例子说的是找到所有可能的句子。就像它显示如何找到“猫和狗”或“猫和狗”所以我的观点是,如果有人说回溯在这里很重要,可能是因为你没有解决真正的问题。backtracking
算法不是从任何事情的后面开始的,它是一种通过(概念上的)搜索空间并在遇到死胡同时进行的算法(或预期的多个解决方案或类似条件的一个解决方案)沿着它穿过搜索空间的路径回溯
,直到它到达一个(概念性的)交叉点,然后从该交叉点开始另一个(概念性的)前进的道路。想象一下,你正在应用一种盲算法来寻找走出迷宫的路——当你走到一条死胡同时,你将返回到最后一个路口,然后走另一条路。@Carter,我的解决方案找到了所有可能的句子。第一个解决方案被提交并接受。后一个解决方案实际上是相同的,但在实践中失败了一个例子。请注意“words”是一个数组列表,其中包含所有可能的句子。@高性能分数感谢回溯算法的澄清。这里你认为我在使用回溯吗?我想我是。对于字符串“catsanddog”,我们可以继续使用每个字母,例如,如果“c”,则以“c”开头在dictionary中,解析rest,如果解析了rest,则与c+rest组合。如果不是,则返回并继续使用“ca”.这和在迷宫中找路一样。是的,刚刚找到了这个…我还尝试了反向字符串。谢谢。所以算法反向跟踪只是一个名称,并不意味着它应该从后面开始,是吗?@Jimmy你可以从任何地方开始。