这个简单的算法,我想有一个优雅的实施方法具有以下(或类似)签名:如何优雅地实现斯卡拉
def increasingSubsequences(xs: List[Int]): List[List[Int]]
它所做的是它分裂没有重新排序的输入序列元素使得结果中的每个子序列都严格增加。
我实现它自己如下:
def increasingSubsequences(list: List[Int], temp: List[Int] = Nil, res: List[List[Int]] = Nil): List[List[Int]] = {
(list, temp) match {
case (x :: xs, t :: ts) if t < x => increasingSubsequences(xs, x :: temp, res)
case (x :: xs, Nil) => increasingSubsequences(xs, List(x), res)
case _ if list.nonEmpty => increasingSubsequences(list, Nil, temp.reverse :: res)
case _ if temp.nonEmpty => (temp.reverse :: res).reverse
case _ => res.reverse
}
}
虽然上面的代码也不是很长,我希望看到一个更优雅和简洁的解决方案,如果可能的(可能通过使用组合程序)。
样品的输入和输出:
List(5, 6, 2, 3, 4, 1, 2, 6, 8, 5) —> List(List(5, 6), List(2, 3, 4), List(1, 2, 6, 8), List(5))
List() —> List()
List(1, 2, 3, 4, 5) —> List(1, 2, 3, 4, 5)
List(5, 4, 3, 2, 1) —> List(List(5), List(4), List(3), List(2), List(1))
谢谢你,宏伟的一段代码。请接受我的编辑建议(您的原始代码返回List(List()),而不是Nil输入。 –