|
步骤2的递归代码(在ChatGPT基础上修改)。
核心就是这总分的递归。其他都很容易实现,不过工作量大。
- Sub GenerateCombinations()
- Dim inputArray() As Variant
- Dim outputArray() As Variant
- Dim tempArray() As Variant
- Dim n As Integer
- Dim i As Integer, j As Integer
- Dim s$
-
- ' 输入数组
- inputArray = Array(1, 2, 3, 4, 5, 6) ', ... '更多数组元素)
-
- ' 设置取数个数
- n = 4 ' 可以根据需要设置
-
- ReDim outputArray(1 To Application.WorksheetFunction.Combin(Application.count(inputArray), n), 1 To n)
- ReDim tempArray(1 To n)
-
- ' 生成组合
- GenerateCombination inputArray, tempArray, outputArray, n, 1, 1, 0 ' 添加额外的参数 1
-
- '输出组合结果
- For i = 1 To UBound(outputArray)
- s = ""
- For j = 1 To n
- s = s & "," & outputArray(i, j)
- Next j
- Debug.Print Mid(s, 2)
- Next i
-
- End Sub
- Sub GenerateCombination(inputArray() As Variant, tempArray() As Variant, outputArray() As Variant, n As Integer, currentIndex As Integer, outputIndex As Integer, startIndex As Integer) ' 添加额外的参数 startIndex
- Dim i As Integer
-
- If currentIndex > n Then
- For i = 1 To n
- outputArray(outputIndex, i) = tempArray(i)
- Next i
- outputIndex = outputIndex + 1 ' 更新 outputIndex 的值
- Exit Sub
- End If
-
- For i = startIndex To UBound(inputArray)
- tempArray(currentIndex) = inputArray(i)
- GenerateCombination inputArray, tempArray, outputArray, n, currentIndex + 1, outputIndex, i + 1
- Next i
- End Sub
复制代码 |
评分
-
2
查看全部评分
-
|