When the function is nested inside another function
def solution():
count = 0 # Enclosing variable
def dfs():
nonlocal count # Declare count as nonlocal to modify it
count += 1
dfs() # Call dfs to increment count
print(count) # Output: 1
solution()
when it is not enclosed in another function
choices = [1,3,4]
n=5
count = 0
def dfs(cur_sum):
global count,n
if cur_sum==n:
count+=1
return
elif cur_sum>n:
return
for choice in choices:
cur_sum+=choice
# if cur_sum<n:
dfs(cur_sum)
cur_sum-=choice
dfs(0)
print(count)