我正在尝试编写 vb.net 代码以返回集合的唯一组合 我的集合包含 3 个不同的元素。我在这篇文章中找到了类似的帖子,但找不到任何 VB 解决方案来获得此结果
例子:
元素:1、2、3
{ 1, 2, 3}
结果必须是
1
2
3
12
13
23
123
...........
>...................
我,我试图通过使用以下代码来实现这一点
Function GetCombinations(ByVal depth As Integer, ByVal values As String()) As IEnumerable(Of String)
If depth > values.Count + 1 Then Return New List(Of String)
Dim result = New List(Of String)
For i = 0 To depth - 1
For y = 0 To values.Count - 1
If i = 0 Then
result.Add(values(y))
Else
result.Add(values(i - 1) + values(y))
End If
Next
Next
Return result
End Function
得到结果
Dim reslt = GetCombinations(4, data_array)
?reslt
Count = 12
(0): "1"
(1): "2"
(2): "3"
(3): "11"
(4): "12"
(5): "13"
(6): "21"
(7): "22"
(8): "23"
(9): "31"
(10): "32"
(11): "33"
提示:我使用数学并设法计算组合数。我可以用这个公式测试
例如,这个公式称为 nCr。这意味着在 n 个元素中,有多少种方法可以取 r 个元素与 r 的唯一组合。
nPr = n!/(n-r)!
n! = 1 * 2 * 3 * 4* ... (n-1) * n
Elements: 1, 2, 3
In this case n = 3 and r can be 1, 2, and 3 all
number of combinations = 3P1 + 3P2 + 3P3
= 3!/2! + 3!/1! + 3!/0!
= 6/2 + 6/1 + 6/1 (0!=1)
= 3+6+6
= 15