subsequences of length n from list performance

前端 未结 4 569
借酒劲吻你
借酒劲吻你 2020-12-05 22:07

I implemented a version of this answer https://stackoverflow.com/a/9920425/1261166 (I don\'t know what was intended by the person answering)

sublistofsize 0          


        
4条回答
  •  萌比男神i
    2020-12-05 22:30

    An optimization which should help is to keep track of whether there are enough elements in the list to form the rest of the subsequence. This can be done very efficiently by keeping track of a pointer which is n-1-elements ahead of xs and advancing them both as you recurse.

    An implementation:

      nthtail 0 xs = xs
      nthtail _ [] = []
      nthtail n (x:xs) = nthtail (n-1) xs
    
      subseq 0 _ = [[]]
      subseq n xs =
        if null t
          then []
          else go n xs t
        where
          t = nthtail (n-1) xs  -- n should always be >= 1 here
          go 0 _ _  =  [[]]
          go _ _ [] = []
          go n xs@(x:xt) t = withx ++ withoutx
            where withx = map (x:) $ go (n-1) xt t
                  withoutx = go n xt (tail t)
    

提交回复
热议问题