Skip to content

Instantly share code, notes, and snippets.

@elazarg
Created December 22, 2017 11:13
Show Gist options
  • Save elazarg/d2565afd43a58fdbe875a7f723ca2cbc to your computer and use it in GitHub Desktop.
Save elazarg/d2565afd43a58fdbe875a7f723ca2cbc to your computer and use it in GitHub Desktop.
subset sum with memoization
from random import randrange
from functools import lru_cache
from bisect import bisect_right
arr = [randrange(100000) for _ in range(2000)]
arr.sort()
import sys
sys.setrecursionlimit(20000)
@lru_cache()
def subsum(n, i=len(arr)-1) -> bool:
assert n < 100000
if i < 0 or n < 0:
return False
if n == 0:
return True
i = bisect_right(arr, n, hi=i)
return subsum(n - arr[i], i - 1) or subsum(n, i - 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment