Created
December 22, 2017 11:13
-
-
Save elazarg/d2565afd43a58fdbe875a7f723ca2cbc to your computer and use it in GitHub Desktop.
subset sum with memoization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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