之前教过大家如何列出 n 个字符中的 m 种排列组合。当时的案例对字符的排列顺序没有要求。
网友提问:如果要列出所有不同顺序的排列组合,又该怎么做呢?
今天来为大家解答。
案例:
列出下图 1 的 A 列中 5 字符中任意 3 个字符的所有排列组合形式。同样的三个字符,如果排列顺序不同要全部列出。
效果如下图 2 所示。


解决方案:
1. 按 Alt+F11 打开 VBE --> 输入以下代码:

Sub GeneratePermutations()
Dim ws As Worksheet
Dim inputRange As Range
Dim outputRange As Range
Dim chars() As String
Dim resultCount As Long
' 设置工作表和范围
Set ws = ThisWorkbook.Sheets(1)
Set inputRange = ws.Range("A2:A6")
Set outputRange = ws.Range("B2")
' 清空输出区域
outputRange.Resize(1000, 1).ClearContents
' 从A列读取字符
ReDim chars(1 To inputRange.count)
Dim i As Integer
For i = 1 To inputRange.count
chars(i) = inputRange.Cells(i, 1).Value
Next i
' 生成排列组合
resultCount = 0
Call Permute(chars, 3, outputRange, resultCount)
MsgBox "共生成 " & resultCount & " 种排列组合", vbInformation
End Sub
Sub Permute(chars() As String, depth As Integer, outputRange As Range, ByRef count As Long, _
Optional currentStr As String = "", Optional usedIndices As String = "")
Dim i As Integer
' 达到所需深度时输出结果
If Len(currentStr) = depth Then
count = count + 1
outputRange.Offset(count - 1, 0).Value = currentStr
Exit Sub
End If
' 递归生成排列
For i = LBound(chars) To UBound(chars)
' 检查该字符是否已被使用
If InStr(usedIndices, "|" & i & "|") = 0 Then
' 递归调用
Call Permute(chars, depth, outputRange, count, _
currentStr & chars(i), usedIndices & "|" & i & "|")
End If
Next i
End Sub
2. 点击“运行”按钮运行代码。

会弹出一个提示框,告诉我们有多少种排列组合。

以下就是所有结果。
