非递归生成所有排列(knuth)

本文介绍了一种使用Knuth算法生成指定数量元素的所有可能排列的方法。该算法通过一系列交换操作来遍历所有可能的排列组合,并且提供了一个VBA实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

'knuth给的算法

'生成所有排列
Option Explicit

Dim result, counter
const N = 4
const Format = 10

Sub Swap(byRef InArray, first, second)

Dim t
= InArray(first)
InArray(first) 
= InArray(second
InArray(
second= t

End Sub

Function GenPer(byRef counter, N, Format)

Dim c(10), o(10) ,t(10)
Dim I, j, s, q, result
Dim oLoopFlag, iLoopFlag

For I = 0 To N - 1
     c(I) 
= 0
     o(I) 
= 1
     t(I) 
= I
Next

oLoopFlag 
= True
counter 
= 0

While oLoopFlag

   
For I = 0 To N - 1
    result 
= result & t(I)
   
Next

   result 
= result & " "
   counter 
= counter + 1

   
If counter Mod Format = 0 Then
    result 
= result & chr(13& chr(10)
   
End If

   j 
= N - 1
   s 
= 0
   iLoopFlag 
= True

   
While iLoopFlag
    q 
= c(j) + o(j)
    
If q > j or q < 0 Then
     
If j = 1 Then
      iLoopFlag 
= False
      oLoopFlag 
= False
     
Else 
      
If q > j Then
      s 
= s + 1
      
End If
      o(j) 
= -o(j)
      j 
= j - 1
     
End If
    
Else
     Swap t, j 
- c(j) + s, j - q + s
     c(j) 
= q
     iLoopFlag 
= False
    
End If
   
Wend

Wend

Genper 
= result

End Function

result 
= GenPer(counter, N, Format)
result 
= result & chr(13& chr(10& "总数:" & counter

MsgBox(result)
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值