给定一个向量
x <- c(4,5,6,7,8,9,10,11,12,13,15,14,13,12,11,10,9,8,6)
查找所有最长的递增子序列 (LIS)
解决方案应该看起来像
4,5,6,7,8,9,10,11,12,13,14
4,5,6,7,8,9,10,11,12,13,15
我什至可以使用元素的索引
我使用了JINJING XIE给出的代码,但它只返回一个序列
任何帮助,将不胜感激
给定一个向量
x <- c(4,5,6,7,8,9,10,11,12,13,15,14,13,12,11,10,9,8,6)
查找所有最长的递增子序列 (LIS)
解决方案应该看起来像
4,5,6,7,8,9,10,11,12,13,14
4,5,6,7,8,9,10,11,12,13,15
我什至可以使用元素的索引
我使用了JINJING XIE给出的代码,但它只返回一个序列
任何帮助,将不胜感激
Here is a (slow & not very efficient) function that will compute it (uses RcppAlgos
)
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
There are for sure ways to make it more efficient, e.g. other logic or by writing it in c++
and using Rcpp
for the whole task.