R:打印所有最长递增子序列(LIS)
给定向量R:打印所有最长递增子序列(LIS),r,dynamic,lis,R,Dynamic,Lis,给定向量 x <- c(4,5,6,7,8,9,10,11,12,13,15,14,13,12,11,10,9,8,6) 我甚至可以使用元素的索引 我使用了由给出的代码,但它只返回一个序列 如果您有任何帮助,我们将不胜感激。这里有一个(速度慢且效率不高)函数可以计算它(使用RcppAlgos) max_sub_sequences 0)返回(x) N谢谢!效果很好,你是对的,它有点慢。我正在尽量减少计算时间。感谢您的帮助。由于内存限制x@jonnyblue8是的,对于单调性很小的大向量,它
x <- c(4,5,6,7,8,9,10,11,12,13,15,14,13,12,11,10,9,8,6)
我甚至可以使用元素的索引
我使用了由给出的代码,但它只返回一个序列
如果您有任何帮助,我们将不胜感激。这里有一个(速度慢且效率不高)函数可以计算它(使用RcppAlgos
)
max_sub_sequences 0)返回(x)
N谢谢!效果很好,你是对的,它有点慢。我正在尽量减少计算时间。感谢您的帮助。由于内存限制x@jonnyblue8是的,对于单调性很小的大向量,它也会失败。最好的方法可能是编辑找到的代码,使其返回所有值(或找到一个算法),然后在Rcpp
中实现,以提高效率。我会编辑我的答案,如果我能找到答案的话。
4,5,6,7,8,9,10,11,12,13,14
4,5,6,7,8,9,10,11,12,13,15
max_sub_sequences <- function (x) {
# x incresing, result is obviously x
if (all(diff(x) > 0)) return (x)
N <- length(x)
n <- N - 1L
break_condition <- TRUE
while (break_condition) {
# generate all combinations of indices
combinations <- RcppAlgos::comboGeneral(1:N,n)
# get subsequences according to indices
sub_sequences <- matrix(x[combinations[1:nrow(combinations),]], nrow = nrow(combinations)) ; rm(combinations)
# check monotony
index_subsequence <- vapply(1:nrow(sub_sequences), function (k) any(diff(sub_sequences[k,]) < 1L), logical(1L))
# keep increasing sequences only
sub_sequences <- sub_sequences[!index_subsequence,] ; rm(index_subsequence)
break_condition <- nrow(sub_sequences) == 0L
n <- n - 1L
}
sub_sequences
}
max_sub_sequences(c(4,5,6,7,8,9,10,11,12,13,15,14,13,12,11,10,9,8,6))
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]
# [1,] 4 5 6 7 8 9 10 11 12 13 15
# [2,] 4 5 6 7 8 9 10 11 12 13 14
# timing
# Unit: seconds
# expr min lq mean median uq max neval
# max_sub_sequences(x) 1.30611 1.462473 1.502727 1.484785 1.522796 1.821037 100