为了在 R 中实现Heap 算法,这里有一个解决方案,将结果输出到矩阵中以供进一步处理:
h <- function(s, n, e, ...) {
## processes Heap's algorithm
if (n == 1L) {
e$i <- e$i + 1L
e$r[e$i, ] <- e$s
} else {
h(s, n - 1L, e)
for (i in 1:(n - 1L)) {
if (n %% 2L == 0L) {
j <- i
} else {
j <- 1L
}
tmp <- e$s[n]
e$s[n] <- e$s[j]
e$s[j] <- tmp
h(s, n - 1L, e)
}
}
}
hperm <- function(s) {
## wrapper
e <- environment()
l <- length(s)
i <- 0L
e$r <- matrix(NA, factorial(l), l)
h(s, l, e, i)
return(e$r)
}
给出:
A <- 0:3
hperm(A)
# [,1] [,2] [,3] [,4]
# [1,] 0 1 2 3
# [2,] 1 0 2 3
# [3,] 2 0 1 3
# [4,] 0 2 1 3
# [5,] 1 2 0 3
# [6,] 2 1 0 3
# [7,] 3 1 0 2
# [8,] 1 3 0 2
# [9,] 0 3 1 2
# [10,] 3 0 1 2
# [11,] 1 0 3 2
# [12,] 0 1 3 2
# [13,] 0 2 3 1
# [14,] 2 0 3 1
# [15,] 3 0 2 1
# [16,] 0 3 2 1
# [17,] 2 3 0 1
# [18,] 3 2 0 1
# [19,] 3 2 1 0
# [20,] 2 3 1 0
# [21,] 1 3 2 0
# [22,] 3 1 2 0
# [23,] 2 1 3 0
# [24,] 1 2 3 0
另请参阅: 堆栈溢出上堆算法的Python 代码。