您可以通过在递归生成排列时检查有效单词来加快速度,而不是生成排列然后尝试将它们分解为单词的两阶段解决方案。如果在任何时候您当前的部分完整排列不对应任何有效单词,请停在那里并且不要进一步递归。这意味着您不会浪费时间生成无用的排列。例如,如果生成“tt”,则无需排列“peanubuter”并将所有排列附加到“tt”,因为没有以tt开头的英文单词。
假设您正在进行基本的递归排列生成,请跟踪您生成的当前部分单词。如果在任何时候它是一个有效的单词,您可以输出一个空格并开始一个新单词,并递归地排列剩余的字符。您还可以尝试将剩余的每个字符添加到当前的部分单词中,并且只有在这样做会导致有效的部分单词(即存在以这些字符开头的单词)时才会递归。
类似这样的东西(伪代码):
void generateAnagrams(String partialAnagram, String currentWord, String remainingChars)
{
// at each point, you can either output a space, or each of the remaining chars:
// if the current word is a complete valid word, you can output a space
if(isValidWord(currentWord))
{
// if there are no more remaining chars, output the anagram:
if(remainingChars.length == 0)
{
outputAnagram(partialAnagram);
}
else
{
// output a space and start a new word
generateAnagrams(partialAnagram + " ", "", remainingChars);
}
}
// for each of the chars in remainingChars, check if it can be
// added to currentWord, to produce a valid partial word (i.e.
// there is at least 1 word starting with these characters)
for(i = 0 to remainingChars.length - 1)
{
char c = remainingChars[i];
if(isValidPartialWord(currentWord + c)
{
generateAnagrams(partialAnagram + c, currentWord + c,
remainingChars.remove(i));
}
}
}
你可以这样称呼它
generateAnagrams("", "", "peanutbutter");
您可以通过传递与当前部分完成的单词对应的 trie 中的节点以及将 currentWord 作为字符串传递来进一步优化此算法。这将使您的isValidPartialWord 检查更快。
您可以通过更改isValidWord 检查来强制唯一性,以仅在单词与前一个单词输出相比按字母升序(大于或等于)字母顺序时才返回true。最后,您可能还需要再次检查是否有欺骗,以发现可以输出两个相同单词的情况。