check this sample code for backtracking, there are two ways I can append the variable i to curr before backtracking, the one here (not commented) updates the global ans array, whereas the other way doesn't (shown below).:
n = 4
k = 2
ans = []
def backtrack(first, curr):
if len(curr)==k:
ans.append(curr)
for i in range(first, n+1):
# curr.append(i)
backtrack(i+1, curr+[i])
# curr.pop()
curr = []
backtrack(1, curr)
print("result = ",ans)
output here: result = [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
for the other way:
n = 4
k = 2
ans = []
def backtrack(first, curr):
if len(curr)==k:
ans.append(curr)
for i in range(first, n+1):
curr.append(i)
backtrack(i+1, curr)
curr.pop()
curr = []
backtrack(1, curr)
print("result = ",ans)
output here: result = [[], [], [], [], [], []]
I wish to understand, what exactly changes here and why the global output array ans behaves differently