How to determine the longest increasing subsequence using dynamic programming?

前端 未结 19 2589
醉梦人生
醉梦人生 2020-11-22 10:55

I have a set of integers. I want to find the longest increasing subsequence of that set using dynamic programming.

19条回答
  •  温柔的废话
    2020-11-22 11:32

    Here is a Scala implementation of the O(n^2) algorithm:

    object Solve {
      def longestIncrSubseq[T](xs: List[T])(implicit ord: Ordering[T]) = {
        xs.foldLeft(List[(Int, List[T])]()) {
          (sofar, x) =>
            if (sofar.isEmpty) List((1, List(x)))
            else {
              val resIfEndsAtCurr = (sofar, xs).zipped map {
                (tp, y) =>
                  val len = tp._1
                  val seq = tp._2
                  if (ord.lteq(y, x)) {
                    (len + 1, x :: seq) // reversely recorded to avoid O(n)
                  } else {
                    (1, List(x))
                  }
              }
              sofar :+ resIfEndsAtCurr.maxBy(_._1)
            }
        }.maxBy(_._1)._2.reverse
      }
    
      def main(args: Array[String]) = {
        println(longestIncrSubseq(List(
          0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)))
      }
    }
    

提交回复
热议问题