List 最长递增子序列中的OCaml搜索

List 最长递增子序列中的OCaml搜索,list,ocaml,List,Ocaml,我试图在列表中找到最长的递增子序列。 我有问题吗? 有什么建议吗? 比如说 [-5;6;7;8;-1;6;7;8;9;10;11;12] The answer should be [-1;6;7;8;9;10;11;12] 下面的代码片段回答了您的问题,IMHO let longest l = let rec aux nbest best ncurr curr = function | [] -> List.rev best | hd :: tl when hd &l

我试图在列表中找到最长的递增子序列。 我有问题吗? 有什么建议吗? 比如说

[-5;6;7;8;-1;6;7;8;9;10;11;12]
The answer should be [-1;6;7;8;9;10;11;12]

下面的代码片段回答了您的问题,IMHO

let longest l =
  let rec aux nbest best ncurr curr = function
    | [] -> List.rev best
    | hd :: tl when hd <= List.hd curr -> (* new sequence *)
        aux nbest best 1 [hd] tl
    | hd :: tl when nbest > ncurr ->
        aux nbest best (ncurr + 1) (hd :: curr) tl
    | hd :: tl ->
        aux (ncurr + 1) (hd :: curr) (ncurr + 1) (hd :: curr) tl
  in
  if l = [] then [] else aux 1 [List.hd l] 1 [List.hd l] (List.tl l)

let test = [-5; 6; 7; 8; -1; 6; 7; 8; 9; 10; 11; 12]

let () =
  List.iter (Printf.printf "%i ") (longest test)
l=
让rec aux nbest best ncurr curr=函数
|[]->List.rev最佳
|hd::tl当hd(*新序列*)
辅助nbest最佳1[hd]tl
|当nbest>ncurr->
辅助nbest最佳(ncurr+1)(高清::当前)tl
|hd::tl->
辅助系统(ncurr+1)(hd::curr)(ncurr+1)(hd::curr)tl
在里面
如果l=[]则[]否则辅助1[List.hd l]1[List.hd l](List.tl l)
让测试=[-5;6;7;8;-1;6;7;8;9;10;11;12]
让()=
List.iter(Printf.Printf“%i”)(最长测试)

请注意,它将返回第一个严格递增的序列,并且nbest和ncurr仅出于性能原因而存在。我看不到任何方法可以避免List.rev操作。函数是尾部递归的。

它是“OCaml”。谢谢。如果l=[],我会重写这行
,然后[]else aux 1[List.hd l]1[List.hd l](List.tl)
通过
将l与[]->[]->[]\hd::tl->aux 1[hd]1[hd]tl
匹配。