sicp 2.43

Exercise 2.43.  Louis Reasoner is having a terrible time doing exercise 2.42. His queens procedure seems to work, but it runs extremely slowly. (Louis never does manage to wait long enough for it to solve even the 6× 6 case.) When Louis asks Eva Lu Ator for help, she points out that he has interchanged the order of the nested mappings in the flatmap, writing it as

 

(flatmap
 (lambda (new-row)
   (map (lambda (rest-of-queens)
          (adjoin-position new-row k rest-of-queens))
        (queen-cols (- k 1))))
 (enumerate-interval 1 board-size))

 

Explain why this interchange makes the program run slowly. Estimate how long it will take Louis's program to solve the eight-queens puzzle, assuming that the program in exercise 2.42 solves the puzzle in time T.

 

 

主要时间开销在于(queen-cols (- k 1))的递归调用。设问题规模为n,考虑递归调用树,原实现n层,每层1个节点,总数O(n);Louis的实现,第二层开始n个节点,每个节点n个子节点,一共n层,总数为O(n^n)。所以后者的执行时间大约是前者的O(n^n)倍

你可能感兴趣的:(SICP)