# lec23 - Straightforward implementation of fib has...

This preview shows pages 1–2. Sign up to view the full content.

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: (* Straightforward implementation of fib has exponential number of * recursive calls. Requires n non-negative. *) let rec fib(n) = if n<2 then 1 else fib(n-1) + fib(n-2) (* However most of these recursive calls share common subproblems - * there are only n distinct subproblems to solve, one for each value * of n. Idea of memoization is to keep track of these results as so * they can be looked up rather than re-computed. *) let fibm(n) = let memo: int option array = Array.create (n+1) None in let rec f_mem(n) = match memo.(n) with Some result -> result (* computed already! *) | None -> let result = if n<2 then 1 else f_mem(n-1) + f_mem(n-2) in memo.(n) <- (Some result); (* record in table *) result in f_mem(n) (* Maximum weight independent set in a tree, office party optimization * problem. *) module Unmemoized = struct type tree = Empty | Node of int * tree * tree (* Returns optimum fun for t. *) let rec party(t) = max (party_in t) (party_out t) (* Returns optimum fun for t assuming the root node of t * is included. *) and party_in(t) = match t with Empty -> 0 | Node(v,left,right) -> v + party_out(left) + party_out(right) (* Returns optimum fun for t assuming the root node of t * is excluded. *) and party_out(t) = match t with Empty -> 0 | Node(v,left,right) -> party(left) + party(right) end e module Memoized = struct (* This version memoizes the optimal fun value for each tree node....
View Full Document

## This note was uploaded on 10/25/2009 for the course PHYS 2214 at Cornell.

### Page1 / 4

lec23 - Straightforward implementation of fib has...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online