Skip to content

Instantly share code, notes, and snippets.

@orb
Forked from siscia/find-solution-seq-to-num.clj
Last active December 20, 2015 02:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save orb/6054330 to your computer and use it in GitHub Desktop.
Save orb/6054330 to your computer and use it in GitHub Desktop.
(defn can-sum-to-zero
([nums]
(can-zero nums #{}))
([nums can-sum-to]
(when (seq nums)
(let [num (first nums)]
(if (can-sum-to (- num))
true
(let [can-also-sum-to (map #(+ num %) can-sum-to)]
(recur (rest nums)
(clojure.set/union can-sum-to can-also-sum-to #{num}))))))))
@orb
Copy link
Author

orb commented Jul 22, 2013

This approach is a breadth first search of all the possible sums you can reach starting from the beginning of the list. It has the advantage of being able to prune subsets that sum to the same value, but since it does need to keep all the sums it can require more memory

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment