整数组合的总和【难度:2级】:
答案1:
from itertools import combinations_with_replacement
def find(arr,n):
return sum( sum(c) == n for x in range(1,len(arr)+1) for c in combinations_with_replacement(arr, x) )
答案2:
def find(arr,n):
return(findl(arr,n,len(arr)))
def findl(arr,n,l):
return(sum(findl(arr[1:],n-arr[0]*i,l-i) for i in range(l+1)) if ((arr) and (l>0)) else ((n==0) and (l>=0)))
答案3:
from itertools import combinations_with_replacement as c
def find(arr, n):
return sum(
sum(xs) == n
for i in range(len(arr))
for xs in c(arr, i + 1)
)
答案4:
from itertools import combinations_with_replacement as cr
find=lambda a,n:sum(n==sum(c)for r in range(1,len(a)+1)for c in cr(a,r=r))
答案5:
def N(Q,S,R,L,D,C,I) :
if 0 < D and 0 < S :
for I in range(I,L) :
N(Q,S - Q[I],R,L,D - 1,C + (Q[I],),I)
elif 0 == S :
R.add(C)
return R
def find (Q,S) :
Q = sorted(set(Q))
return len(N(Q,S,set(),len(Q),len(Q),(),0))
答案6:
from itertools import combinations_with_replacement
def find(arr,n):
ret = 0
for i in range(1, len(arr) + 1):
a = combinations_with_replacement(arr, i)
ret += len([j for j in a if sum(j) == n])
return ret
答案7:
from itertools import combinations_with_replacement
def find(arr, n):
return sum(sum(x) == n for i in range(1, len(arr) + 1) for x in combinations_with_replacement(arr, i))
答案8:
from itertools import combinations_with_replacement as cr
def find(arr,n):
k=len(arr)
return sum((1 for nn in range(k) for x in cr(arr,nn+1) if sum(x)==n))
答案9:
from itertools import combinations_with_replacement as cr
def find(arr,n):
k=len(arr)
return len([x for nn in range(k) for x in cr(arr,nn+1) if sum(x)==n])
答案10:
from itertools import combinations_with_replacement as cwr
def find(arr, n):
all_combos = []
for i in range(1, len(arr)+1):
combos = list(cwr(arr, i))
all_combos += combos
c = 0
for el in all_combos:
if sum(el) == n:
c += 1
return c