# input: a[0..N) array of integers, N>=0, and S## output: is there a subarray of a[0..N) whose sum is S?## O(NS) time and space solutiondefss_tab(a,S):N=len(a)tab=[[Noneforsinrange(S+1)]forninrange(N+1)]forsinrange(S+1):tab[0][s]=(s==0)n,s=1,0whilen!=N+1:ifs==S+1:n,s=n+1,0else:tab[n][s]=tab[n-1][s]iftab[n][s]==Falseanda[n-1]<=s:tab[n][s]=tab[n-1][s-a[n-1]]s+=1returntab[N][S]
Comments (0)
HTTPSSSH
You can clone a snippet to your computer for local editing.
Learn more.