-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTarget sum.py
More file actions
40 lines (35 loc) · 779 Bytes
/
Target sum.py
File metadata and controls
40 lines (35 loc) · 779 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
N = 5
arr = [1, 1, 1, 1, 1]
t = 3
def target(arr,N,target):
sm=sum(arr)
p1=sm+target
dp={}
arr.sort(reverse=True)
if p1%2!=0:
return 0
else:
p1=p1//2
def solve(n,p1):
if n==0:
if p1==0:
return 1
else:
return 0
elif (n,p1) in dp:
return dp[(n,p1)]
else:
item=arr[n-1]
if item<=p1:
c1=solve(n-1,p1-item)
c2=solve(n-1,p1)
c=c1+c2
else:
if p1==0:
c=1
else:
c=0
dp[(n,p1)]=c
return c
print(solve(N,p1))
target(arr,N,t)