我有这段代码:
Dim combinations As New List(Of String)
Dim word As String = "abc"
For c1 = 0 To word.Length - 1
combinations.Add(word(c1))
For c2 = 0 To word.Length - 1
If c2 <> c1 Then
combinations.Add(word(c1) & word(c2))
For c3 = 0 To word.Length - 1
If c3 <> c2 And c3 <> c1 Then
combinations.Add(word(c1) & word(c2) & word(c3))
End If
Next
End If
Next
Next
输出:
a, ab, abc, ac, acb, b, ba, bac, bc, bca, c, ca, cab, cb, cba
如何创建一个函数,它可以为无限的字长做同样的事情?
答案 0 :(得分:1)
Backtracking是一种很好的方法。基本上,您可以随时构建各种输入的图表,添加下一个可用的输出,直到用完为止,然后备份并删除一个,并将其替换为另一个。这是another explanation。
答案 1 :(得分:0)
我不是vb.net编码器,但看到这是一个有趣的练习。这是我在伪代码中的答案:
array A = ('a','b','c') //add all the unique letters to an array
integer COUNT = length of A
array P = A //initialize P (the final answer) as A
array L = A //initialize L as A to start
for j=2 to COUNT {
array N = () //new empty array
foreach i in L { //loop through all the elements of L
foreach m in A { //loop through all the elements of A
if (i does not contain m) {
push (i + m) into P //push the concatenation of i & m into array P
push (i + m) into N //do the same thing for array N the next loop through
}
}
}
L = N
}
change P to a string or whatever you want the output to be....