【问题标题】:scheme calculating combination nCk using memoization使用记忆化计算组合 nCk 的方案
【发布时间】:2016-10-28 02:41:54
【问题描述】:

我正在尝试计算 nCk 在球拍/方案中使用记忆的组合方式

我不能使用单独的递归方法来计算 n!。 我已经做到了这一点,但是说这是不好的语法 我实际上修复了错误的语法错误! 但在 (let ([ans (assoc (x y) memo part!. 有谁知道我做错了什么?

 (define combm
  (letrec ([memo null]
           [f (lambda (x y)
                (let ([ans (assoc (x y) memo)])
                  (if ans
                      (cdr ans)
                      (let ([new-ans (letrec ([fac (lambda (x)
                                      (if (eq? x 0)
                                          1
                                          (* x (fac (- x 1)))))])
                        (/ (fac x) (* (fac y) (fac (- x y)))))])
                        (begin
                          (set! memo (cons (cons (x y) new-ans) memo))
                          new-ans)))))])
    f))

                                     `

【问题讨论】:

    标签: scheme lisp racket


    【解决方案1】:

    这个表达式(assoc (x y) memo) 是导致错误的原因。

    如果您像(combm 42 43) 一样应用combm,则(assoc (x y) memo) 变为 (assoc (42 43) memo)(42 43) 的意思是“在 43 上应用值 42”。问题是 42 不是函数。

    改用(assoc (list x y) memo)

    【讨论】:

      【解决方案2】:

      这是一个可能的解决方案,它记住了阶乘函数:

      (define combm
        (let ((memo '()))
          (lambda (n r)
            (letrec ((fact (lambda (n)
                             (let ((ans (assoc n memo =)))
                               (if ans
                                   (cadr ans)
                                   (if (< n 2)
                                       1
                                       (let ((res (* n (fact (sub1 n)))))
                                         (set! memo (cons (list n res) memo))
                                         res)))))))
              (/ (fact n) (* (fact r) (fact (- n r))))))))
      

      记忆对于阶乘是必要的,因为它在组合公式中多次使用。

      【讨论】:

      • 谢谢你,我也想通了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-18
      • 1970-01-01
      • 2018-08-22
      • 2013-04-01
      • 2018-10-07
      相关资源
      最近更新 更多