I read about the problem of a subset of sums when I came up with what seems to be a universal algorithm for solving it:
(defun subset-contains-sum (set sum) (let ((subsets) (new-subset) (new-sum)) (dolist (element set) (dolist (subset-sum subsets) (setf new-subset (cons element (car subset-sum))) (setf new-sum (+ element (cdr subset-sum))) (if (= new-sum sum) (return-from subset-contains-sum new-subset)) (setf subsets (cons (cons new-subset new-sum) subsets))) (setf subsets (cons (cons element element) subsets)))))
"set" is a list that does not contain duplicates, and "sum" is the sum to search for subsets. “subsets” is a list of cons cells in which “car” is a list of subsets, and “cdr” is the sum of that subset. New subsets are created from the old O (1) times, simply bypassing the element to the front.
I'm not sure if this is runtime complexity, but it seems that with each element the “sum” grows, the size of the “subsets” doubles, plus one, so it seems to me at least quadratic.
I publish this because, first of all, my impression was that NP-complete problems are usually insoluble and that the best we can hope for can be heuristic, but this seems to be a universal solution, which, let's say cycles CPUs always give the correct answer. How many other NP-complete problems can be solved, like this one?
lisp np-complete subset-sum
Gem
source share