方案 - 列表中总和0的数字的确定性



我正在尝试实现一个递归函数(sums cero),该功能给出了整数列表,它打印了所有可能连续数字的SECUSECTION

示例1:

(Sum -Zero’(4 2 -3 -1 0 4))

=>(-3 -1 0 4)

(0)

示例2:

(Sum -Zero’(3 4 -7 3 1 3 1 -4 -2 -2))

=>(3 4 -7)

(4 -7 3)

(-7 3 1 3)

(3 1 -4)

(3 1 3 1 -4 -2 -2)

(3 4 -7 3 1 3 1 -4 -2 -2)

您的功能需要具有一个有参数为1的助手。。这就是我的方式,有些部分遗漏了我们的作业:

(define (sum-zero lst)
  ;; insert e such that the resulting list i ssorted
  ;; (insert 3 '(1 3 4)) ; ==> (1 3 3 4)
  (define (insert e lst)
    <implement>)
  ;; main logic
  (define (helper lst acc res)
    (if (null? lst)
        res
        (let* ((new-acc (insert (car lst) acc))
               (res (if <should add new-acc to res>
                        (cons new-acc res)
                        res)))
          ;; call the helper skipping the current element in the result
          ;; and use that as the result on the secon call the includes it
          (helper (cdr lst)
                  new-acc                  
                  (helper (cdr lst) acc res)))))
  ;; notice () is already in the results
  (helper lst '() '(())))

测试它很简单。我的结果比您多,但我认为这是正确的:

(sum-zero '(3 4 -7 3 1 3 1 -4 -2 -2))
; ==> ((-7 -4 -2 -2 1 1 3 3 3 4)
;      (-7 -4 -2 3 3 3 4)
;      (-7 -2 -2 1 1 3 3 3)
;      (-7 -4 1 1 3 3 3)
;      (-7 -2 3 3 3)
;      (-7 -2 -2 1 3 3 4)
;      (-7 -4 1 3 3 4)
;      (-7 -2 1 1 3 4)
;      (-7 3 4)
;      (-4 -2 1 1 4)
;      (-4 -2 -2 1 3 4)
;      (-2 -2 4)
;      (-4 4)
;      (-7 1 3 3)
;      (-4 -2 -2 1 1 3 3)
;      (-4 -2 3 3)
;      (-2 1 1)
;      (-2 -2 1 3)
;      (-4 1 3)
;      ())

最新更新