Skip to content

Instantly share code, notes, and snippets.

@michaelsproul
Created October 22, 2014 23:50
Show Gist options
  • Save michaelsproul/ddf87c29de6895291e11 to your computer and use it in GitHub Desktop.
Save michaelsproul/ddf87c29de6895291e11 to your computer and use it in GitHub Desktop.
Haskell Dynamic Programming
-- Recursive and Dynamic Programming solutions to the recurrence N(k) = 2N(k - 3) + N(k - 2)
compute_rec :: Int -> Int
compute_rec 0 = 0
compute_rec 1 = 0
compute_rec 2 = 2
compute_rec k = 2 * (compute_rec (k - 3)) + (compute_rec (k - 2))
compute :: Int -> Int
compute k = cache !! k
where
cache = [0, 0, 2] ++ [2 * (cache !! (k - 3)) + (cache !! (k - 2)) | k <- [3..]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment