我被这个方法弄得晕头转向,我从http://visualbasic.about.com/b/2007/06/06/permutations-recursion-and-traversing-a-binary-tree.htm修改过。我在VB.net中重写了它,尽管似乎需要大量的循环才能完成任何工作,但它很好用。为什么这个递归工作?有人能告诉我为什么这个代码有效吗?
这种方法需要一个单词,并返回该单词中所有字母的变体,沿着它只显示出现在字典中的单词的方式,但那不是问题。
一旦它已经通过单词中的字母,例如abcd,通过a,ab,abc等循环,它就会到达end子节点。
在那里,我希望它停下来。但事实并非如此,这是我感到困惑的一点。它回到递归调用,并再次运行代码从那里到end sub,多次。如果有什么,我会期望它回到sub的顶部,这本身会很奇怪,但是在递归调用之后不会回来。它没有循环整个小组,并且看起来像是从那里开始的。
SUBSECTION OF CODE
PermutationOfLetters()
' Mark this item free again - start again
IsItemUsed(i) = False
' Restore the current Perm
permutationString = PermWord
End If
Next
BGworker.ReportProgress(LoopCounter)
End Sub
它需要做到这一点,以获得分支工作,但我不明白是什么让它做到这一点? 任何人都可以启发我吗?这很难解释“巫毒在这里发生”。
我刚刚注意到与原始代码链接上的另一张海报问了同样的问题。 :-)
所有代码
Private Sub PermutationOfLetters()
'Just a counter to see how many time the Sub loops
Static RecursionCounter As ULong = 0
' lbxWords.Items.Add("recursion " & RecursionCounter)
RecursionCounter += 1
'Just a counter to count how many loops in the For statement
Static LoopCounter As ULong = 0
'chop up the word into a character array w,o,r,d,s
Static WordIntoletters As Char() = myDictionary.SelectedWord.ToCharArray()
Static permutationString As String
' gives a true /false for each letter as it passes through set false to start - Boolean Array
Static IsItemUsed(myDictionary.SelectedWord.Length - 1) As Boolean
Dim PermWord As String = permutationString ' Save the current Perm for each value currently available
'count through each letter and operate on those that are false
For i = 0 To myDictionary.SelectedWord.Length - 1
LoopCounter += 1
'when it finds a false then run the loop
If IsItemUsed(i) = False Then
'add another letter to the word
permutationString += WordIntoletters(i)
If FoundWordsDictionary.ContainsKey(permutationString) = False Then
End If
'if words are in the dictionary output real words and are not already saved
If myDictionary.WordDictionary.ContainsKey(permutationString) = True AndAlso FoundWordsDictionary.ContainsKey(permutationString) = False Then
' lbxWords.Items.Add(i & " " & permutationString)
'pass the words through to the sorted dict for easy output
FoundWordsDictionary.Add(permutationString, permutationString)
' lbxWords.Items.Add(permutationString)
End If
' Mark this item unavailable - finished with a true
IsItemUsed(i) = True 'so don't come back to that letter
PermutationOfLetters()
' Mark this item free again - start again
IsItemUsed(i) = False
' Restore the current Perm
permutationString = PermWord
End If
Next
BGworker.ReportProgress(LoopCounter)
End Sub
为什么不直接在调试模式下运行代码并一次只执行一行?您将以这种方式快速准确地回答问题。 ;) – Crono
完成它,多次,甚至显示其他人。它仍然如此。没有人知道为什么。 – netchicken
这不能是所有代码,因为它引用的是在方法外部定义的变量。因为这个,递归可能会起作用。 – PCG